在嵌套的ifelse语句中使用grepl和其他字符串

时间:2017-12-06 22:33:33

标签: r dplyr grepl

#working example
col1 <- c("cat", "cats", "cat2", "dog", "carrot", "carrots", "broccoli", 
"squash", "tundra", "grassland", "grasslands")
df <- as.data.frame(col1)

我想创建一个新列,用于标识字符串是动物,蔬菜还是生物群落。

期望的输出:

         col1      col2
1         cat    animal
2        cats    animal
3        cat2    animal
4         dog    animal
5      carrot vegetable
6     carrots vegetable
7    broccoli vegetable
8      squash vegetable
9      tundra     biome
10  grassland     biome
11 grasslands     biome

我想了解为什么以下代码的grepl部分不起作用。

df_new <- df %>% mutate(col2 = ifelse(col1 %in% c("dog", grepl("cat", col1)), "animal", 
     ifelse(col1 %in% c(grepl("carrot", col1), "broccoli", "squash"), "vegetable", 
     ifelse(col1 %in% c("tundra", grepl("grassland", col1)), "biome", NA))))

1 个答案:

答案 0 :(得分:1)

grepl会返回一个逻辑向量,您需要grep(..., value=TRUE)

df %>% 
    mutate(col2 = ifelse(col1 %in% c("dog", grep("cat", col1, value=T)), "animal", 
                  ifelse(col1 %in% c(grep("carrot", col1, value=T), "broccoli", "squash"), "vegetable", 
                  ifelse(col1 %in% c("tundra", grep("grassland", col1, value=T)), "biome", NA))))

#         col1      col2
#1         cat    animal
#2        cats    animal
#3        cat2    animal
#4         dog    animal
#5      carrot vegetable
#6     carrots vegetable
#7    broccoli vegetable
#8      squash vegetable
#9      tundra     biome
#10  grassland     biome
#11 grasslands     biome