Skip to content

coalesce() function "Must subset elements with valid subscript vector" #5326

Description

@mlok2u

Hi,

I have historically been able to wrap the coalesce() function with a function that will identify suffixed columns in a dataframe and coalesce accordingly.
However, after updating to v.1.0.0, the functionality appears to be broken due to the following exception:
"Must subset elements with a valid subscript vector."


Brief description of the problem

library(dplyr)

coalesce_df_fields <- function(df, suffix_a, suffix_b) {
  suffix_a <- paste0('(',suffix_a,')$')
  suffix_b <- paste0('(',suffix_b,')$')

  fields_a <- data.frame(fields_a = colnames(df)[grepl(suffix_a, colnames(df))]) %>%
    mutate(root = gsub(suffix_a, '', fields_a))
  
  fields_b <- data.frame(fields_b = colnames(df)[grepl(suffix_b, colnames(df))]) %>%
    mutate(root = gsub(suffix_b, '', fields_b)) %>%
    filter(fields_b != 'not_in_sf')
  
  colname_ref <- fields_a %>% full_join(fields_b, by = 'root')
  ## LOOP: Need to create new field "root" in df that coalesces "fields_a" and "fields_b" values
  df[colname_ref$root] <- coalesce(df[colname_ref$fields_a], df[colname_ref$fields_b])
  
  return(df)
  
}

## use case of the function:

sample_df <- data.frame(id = c('a', 'b', 'c', 'd'),
                 int_x = c(NA, 5, NA, 8),
                 char_x = c('14', NA, 'hello', 'what'),
                 int_y = c(100, 389, 90, 9),
                 char_y = c('this', 'should', 'fill', 'in'))

df <- coalesce_df_fields(sample_df, '_x', '_y')

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorfuns 😆

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions