1

I would like to divide a dataframe (cl) into several blocks and work with them within this dataframe. I proceed to the block ADL:

adlvars<- c("ADL_H1", "ADL_H2", "ADL_H3", "ADL_H4", "ADL_H5", "ADL_H6")

Further, I should convert the factors into character as it prescribed in the FAQ.R

cl[,adlvars] <- as.numeric(levels(cl[,adlvars]))[as.integer(cl[,adlvars])]

There is a warning:

Error: (list) object cannot be coerced to type 'integer'

The second option in the FAQ.R is

cl[,adlvars] <- as.numeric(as.character(cl[adlvars]))

There is a warning message:

NAs introduced by coercion

Table function returns all the values were changed to NAs.

Please help to find a solution. Many thanks!

acylam
  • 18,231
  • 5
  • 36
  • 45
  • This is really confused code. To start with I think you might want `cl <- cl[adlvars]` ... then from there why aren't you using `as.character()` if your goal is to convert to character? – Elin Jun 26 '18 at 17:31
  • 1
    Without seeing the data in `cl`, it's really hard to even understand what you're trying to do. It's also confusing why you would coerce the entire dataframe to character, then to numeric. That's definitely going to introduce NAs. – Anonymous coward Jun 26 '18 at 17:32
  • Also what's confusing is the use of the levels ... `as.numeric(levels(iris$Species))` gives you three NA values. Then you are somehow trying to subset that vector of NAs using a list of variable names... but they will always be NA. – Elin Jun 26 '18 at 18:31
  • What you need to do is to provide a minimal verifiable example, and producing that is going to help you understand the problem and possibly answer your question. What you might do is use the `iris` data set and break your problem into steps. That will help you understand what is going wrong. Then update your question and answer it yourself if you figured it out. – Elin Jun 26 '18 at 18:38
  • I find an answer somewhere on this site: cl[adlvars] <- lapply(cl[adlvars], function(x) as.numeric(as.character(x))) – user9995846 Aug 29 '18 at 13:38

0 Answers0