在特定顺序的变量的特定值上通过case_when突变字符向量

时间:2019-01-29 10:49:14

标签: r dplyr switch-statement mutate

library(dplyr)

df <- tibble(Letters = c("A", "B", "C", "C", "C", "D", "D", "D", "E", "E", "E"))
meta <- c("foo", "bar", "baz")

   Letters
   <chr>  
 1 A      
 2 B      
 3 C      
 4 C      
 5 C      
 6 D      
 7 D      
 8 D      
 9 E      
10 E      
11 E

在这里,我想按照向量的特定顺序将字符向量meta突变为字母CDE

我尝试过类似的事情:

df <- df %>% mutate(New = case_when(Letters %in% c("C", "D", "E") ~
                                   meta %>% rep_len(nrow(df)),
                               TRUE ~ NA_character_))

但是,这会在数据帧的顶部开始矢量化过程,并且CDE的填充顺序为baz,{ {1}},foo,而不是barfoobar

baz

所需的输出:

# A tibble: 11 x 2
   Letters New  
   <chr>   <chr>
 1 A       NA   
 2 B       NA   
 3 C       baz  
 4 C       foo  
 5 C       bar  
 6 D       baz  
 7 D       foo  
 8 D       bar  
 9 E       baz  
10 E       foo  
11 E       bar  

1 个答案:

答案 0 :(得分:1)

假设字符在“字母”列中重复的次数与“元”的长度相同,则只需简单的赋值即可

df$New <- NA
df$New[df$Letters %in% c("C", "D", "E")] <- meta

或使用tidyverse

library(tidyverse)
df %>% 
    group_by(Letters) %>% 
    nest %>%
    mutate(New = case_when(Letters %in% c('C', 'D', 'E') ~ list(meta),
                  TRUE ~ list(NA_character_))) %>% 
    unnest