簡體   English   中英

在嵌套ifelse語句中與其他字符串一起使用grepl

[英]Using grepl in a nested ifelse statement with other strings

#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))))

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM