简体   繁体   English

R:如何一次重新编码多个变量

[英]R: how to do recode for multiple variables at a time

I am trying not to get tangled in loops and complicated code that will take a lot longer to get right than simply repeating lines of code.我试图不纠缠于循环和复杂的代码中,这些代码比简单地重复代码行需要更长的时间才能正确完成。

I want to do the following recode for multiple variables in R.我想对 R 中的多个变量进行以下重新编码。 I concatenated the variables, but they didn't change the content of the original data file.我连接了变量,但它们并没有改变原始数据文件的内容。

recode(d$var1,"1=50; 2=70; 3=100; 4=140; 5=190")

repeat for d$var2 to d$var20 ....重复d$var2d$var20 ....

If it's better use of coding time to copy the code 20 times, just tell me!如果更好地利用编码时间复制代码 20 次,请告诉我!

Many thanks.非常感谢。

Let

d = data.frame(var1 = c(1, 2, 3, 4, 5), 
               var2 = c(1, 2, 3, 4, 5), 
               var3 = c(1, 2, 3, 4, 5))

Then with a simple apply we get然后通过一个简单的apply我们得到

A = apply(d, 
          2, 
         function(x) dplyr::recode(x, "1" = "50", "2" = "70", 
                                       "3" = "100" , "4" = "140", 
                                       "5" = "190")) %>% 
    as.data.frame(stringsAsFactors = FALSE)

the output output

> A
  var1 var2 var3
1   50   50   50
2   70   70   70
3  100  100  100
4  140  140  140
5  190  190  190

If all of your variables are in the same dataframe, you can edit var1:var3 with var1:var999 to recode all of the variables.如果所有变量都在同一个 dataframe 中,则可以使用var1:var999编辑var1:var3以重新编码所有变量。

With dplyr :使用dplyr

A <- d %>%
  mutate_at(vars(var1:var3), .funs = list(
    ~case_when(
      . == 1 ~ 50,
      . == 2 ~ 70,
      . == 3 ~ 100,
      . == 4 ~ 140,
      . == 5 ~ 190
    )
  ))

If you have var1:var3 across multiple dataframes or lists, you could create a function such as:如果您在多个数据帧或列表中有var1:var3 ,您可以创建一个 function,例如:

recode_func <- function(x) {

df <- df %>%
  mutate_at(vars(x), .funs = list(
    ~case_when(
      . == 1 ~ 50,
      . == 2 ~ 70,
      . == 3 ~ 100,
      . == 4 ~ 140,
      . == 5 ~ 190
    )
  ))
}

And then call the function to a dataframe or list.然后调用 function 到 dataframe 或列表。

Gives us:给我们:

  var1 var2 var3
1   50   50   50
2   70   70   70
3  100  100  100
4  140  140  140
5  190  190  190

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM