Coalesce or vctrs? merging variables or converting entire dataframe to numeric


I am working with a survey data set. Each question has three versions one for each language. Most of the data is output in binary or categorical variables. I can use coalesce for any of the integer variables but for any of the ordinal or categorical variables, it gives me an error because the data is logical/atomic.

This code works for the integer variable:
baseline2$gender <- coalesce(baseline2$gender_1,baseline2$gender_2,baseline2$gender_3)

This code doesn't work for the factor or logical variables:
baseline2$age <- coalesce(baseline2$age_1,baseline2$age_2,baseline2$age_3)
Error: Argument 3 must be a factor object, not a logical vector

I tried converting the entire data frame to numeric which really messes up the integer variables. I use code that convert from logical to character to numeric.

I am trying to use to following code to convert the logical to integer variables.

(to.replace <- names(which(sapply(baseline2, is.logical))))
for (var in to.replace) baseline2[, (var)== as.numeric(get(var))]

But it is returning this error:
Error in get(var) : object 'XXXXXXXXX' not found

Goal of what I am trying to do:

  • Convert logical, factor to numeric variables. (already numbers but the variable type according to glimpse is lgl or fct.
  • Coalesce 3 variables, removing NAs
  • Can I use vctrs instead of coalesce? I read that is was supposed to help but haven't really seen much discussion of it being used for coalesce

Thank you!

It would be easier to help with some example data. Either your data (you can use dput() to dump it), or some artificial data that reproduces the difficulties.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.