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

문자열이 동물, 야채 또는 생물체인지 여부를 식별하는 새 열을 만들고 싶습니다.다른 문자열과 함께 중첩 된 ifelse 문에서 grepl 사용

원하는 출력 :

  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)))) 
+2

그것은'case_when'를 사용하는 간단 :'DF %> % 돌연변이 (COL2 = case_when (grepl ('고양이 | 개' grepl ('툰드라 목초지', col1) ~ 'biome'))'또는'룩업 테이블 – alistaire

답변

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 
+1

큰 감사합니다. grepl 대신 grep을 시도했지만 value = T에 대해 알지 못했습니다. –

관련 문제