0

I have a data frame with many columns of integer variables, each representing a particular question on a food frequency questionnaire. I want to recode these columns to numerical variables representing the number of servings of that food eaten per month. mapvalues() in plyr seems like the right function, but I keep getting warning messages because not all of the foods have the full range of responses recorded:

The following `from` values were not present in `x`: 4, 5, 6, 7, 8

Setting warn_missing = false does not return warning messages, but my data are still not being recoded.

Sample code (nails is my data frame, and foodnames is a list of variable names):

for (food in foodnames[c(7:81, 95:97)]){
  mapvalues(eval(parse(text=paste("nails$", food))), from = c(1:8),
            to = c(0, 1, 2.5, 4, 8, 14, 22, 28)), warn_missing = FALSE)
}

How can I get R to recode these variables even if they do not contain all the integers from 1 to 8? Thanks in advance.

Alex P.
  • 1
  • 1
  • 1
    Please show a small reproducible example. We don't need `eval(parse` for this – akrun Dec 08 '15 at 18:30
  • 1
    [Info on how to give a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Dec 08 '15 at 18:34
  • Here's a reproducible example: `df <- structure(list(A = c(6L, 2L, 5L, 4L, 5L, 5L, 5L, 1L, 2L, 3L), B= c(1L, 5L, 3L, 1L, 5L, 1L, 3L, 1L, 5L, 1L), C = c(5L, 7L, 3L, 2L, 6L, 1L, 8L, 3L, 4L, 2L)), .Names = c("A", "B", "C"), row.names = c(NA, 10L), class = "data.frame") for (name in names(df)){ assign(paste("df$", name), mapvalues(eval(parse(text=paste("df$", food))), from = c(1:8),to = c(0, 1, 2.5, 4, 8, 14, 22, 28), warn_missing = TRUE)) }` This gives an error because A and B don't have all 8 integer values. – Alex P. Dec 10 '15 at 23:20
  • On the other hand, this code correctly recodes C: `df$C <- mapvalues(df$C, from = c(1:8),to = c(0, 1, 2.5, 4, 8, 14, 22, 28), warn_missing = TRUE)` – Alex P. Dec 10 '15 at 23:23

0 Answers0