Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to recode multiple variables at once

Tags:

r

dplyr

recode

I have several variables in my dataset that need to be recoded in exactly the same way, and several other variables that need to be recoded in a different way. I tried writing a function to help me with this, but I'm having trouble.

library(dplyr)
recode_liberalSupport = function(arg1){
  arg1 = recode(arg1, "1=-1;2=1;else=NA")
  return(arg1)
}

liberals = c(df$var1, df$var4, df$var8)
for(i in unique(liberals)){
  paste(df$liberals[i] <- sapply(liberals, FUN = recode_liberalSupport))
}

R studio works on this for about 5 minutes then gives me this error message:

Error in `$<-.data.frame`(`*tmp*`, liberals, value = c(NA_real_, NA_real_,  : 
  replacement has 9 rows, data has 64600
In addition: Warning messages:
1: Unknown or uninitialised column: 'liberals'. 
2: In df$liberals[i] <- sapply(liberals, FUN = recode_liberalSupport) :
  number of items to replace is not a multiple of replacement length

Any help would be really appreciated! Thank you

like image 610
Bertrand Avatar asked Feb 07 '18 21:02

Bertrand


1 Answers

This is neater I think with dplyr. Using recode correctly is a good idea. mutate_all() can be used to operate on the whole dataframe, mutate_at() on just selected variables. There are lots of ways to specify variables in dplyr.

mydata <- data.frame(arg1=c(1,2,4,5),arg2=c(1,1,2,0),arg3=c(1,1,1,1))

mydata

  arg1 arg2 arg3
1    1    1    1
2    2    1    1
3    4    2    1
4    5    0    1

mydata <- mydata %>% 
     mutate_at(c("arg1","arg2"), funs(recode(., `1`=-1, `2`=1, .default = NaN)))

mydata

  arg1 arg2 arg3
1   -1   -1    1
2    1   -1    1
3  NaN    1    1
4  NaN  NaN    1

I use NaN instead of NA as it is numeric is be simpler to manage within a column of other numbers.

like image 110
Stephen Henderson Avatar answered Sep 17 '22 21:09

Stephen Henderson