通过mutate和for循环自动分配变量名

时间:2018-10-05 10:16:47

标签: r for-loop dplyr assign mutate

我有一个包含40个变量G1_aG1_b,...到G20_aG20_b(根据调查得出)的数据框。我想创建20个新变量G1 ... G20,以总结现有变量。

data <- data.frame(G1_a = c(0, 0, 0, 1, NA), 
               G1_b = c(0, 0, 1, 1, NA), 
               G2_a = c(0, 0, 0, 1, NA), 
               G2_b = c(0, 0, 1, 1, NA))

# Reshaping without for-loop:
data <- data %>% 
  mutate(G1 = case_when(
    G1_a == 1 ~ "own_offer", 
    G1_b == 1 ~ "no_offer", 
    T ~ NA_character_
  ))

data <- data %>% 
  mutate(G2 = case_when(
    G2_a == 1 ~ "own_offer", 
    G2_b == 1 ~ "no_offer", 
    T ~ NA_character_
  ))

我想在for循环中自动创建新变量,例如:

# Reshaping with for-loop:
for(i in 1:2) {
 data <- data %>% 
   mutate(assign(paste0("G", i), case_when(
     get(paste0("G", i, "_a")) == 1 ~ "own_offer", 
     get(paste0("G", i, "_b")) == 1 ~ "no_offer", 
     T ~ NA_character_
    )))
  }

我的问题包括两个部分:

1)是否可以将assignmutate合并?我知道像mutate(df, !!varname := Petal.width * n)(请参阅here)这样的方法可以动态分配参数名称。但是,我无法将其与要运行的数据重塑结合在一起。

2)dplyr是否允许将paste0case_whenmutate一起使用?

1 个答案:

答案 0 :(得分:2)

这有点棘手,但是我认为这是实现这一目标的原则。最终结果是带有所需列的数据框架,从而避免了所有get() / assign()的麻烦(并且不会在工作区中堆满很多派生变量)。我们分几个步骤使用tidyr::gather()tidyr::spread()更改数据框的形状(宽->长->部分宽->宽)。如果看起来不知所措,请尝试在各个中间点停止管道顺序,以查看到目前为止已取得的成就。

library(tidyr)
library(dplyr)
dds <- (dd
  %>% mutate(case=seq(n()))    ## need a variable to distinguish rows in original data set
  %>% gather(var,val,-case)    ## -> long format: {case, var={G1_a,G1_b,...}, val={0,1,NA}}
  %>% separate(var,c("var","response"))  ## split to "G1","G2" + "a", "b"
  %>% spread(response,val)               ## convert back to semi-wide: {case, var, a, b}
  ## now collapse rows to categorical value, as above
  %>% mutate(offer=case_when(a==1 ~ "own_offer",
                             b==1 ~ "no_offer",
                             TRUE ~ NA_character_))
  %>% select(-c(a,b))          ## clean up now-redundant variables
  %>% spread(var,offer)        ## convert back to wide format: {case, G1, G2, ...}
  %>% select(-case)            ## now redundant
)

结果

         G1        G2
1      <NA>      <NA>
2      <NA>      <NA>
3  no_offer  no_offer
4 own_offer own_offer
5      <NA>      <NA>