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