簡體   English   中英

如何使用 ifelse 使用 mutate 在 R 中獲取新列

[英]How to use ifelse using mutate to get a new column in R

我的數據的一個簡單示例如下所示

 Id xy 12 Yellow Yellow 13 Yellow Blue 10 Blue Yellow 14 Blue Blue 19 Yellow Yellow

我想得到這個

 Id xyz 12 Yellow Yellow Y 13 Yellow Blue N 10 Blue Yellow N 14 Blue Blue N 19 Yellow Yellow Y

當 x 和 y 只是黃色時,我得到 Y,否則 z 列的 N

我試過這個,但它對我沒有幫助。

 dat%>% mutate(z=ifelse(x=="Yellow") & (ifelse(y=="yellow")),"Y","N")

我們不需要兩個ifelse 此外,第一個和第二個的ifelse只有“測試”條件,沒有“是”或“否”,即根據?ifelse ,用法是

ifelse(測試,是,否)

在 OP 的帖子中, ifelsetest條件后關閉

ifelse(y=="yellow")
         ^test condition

對於多個元素,而不是== ,可以使用%in%

dat$z <- c("N", "Y")[Reduce(`&`, lapply(dat[-1], `%in%`, c('yellow', 'Yellow'))) + 1]
dat$z
#[1] "Y" "N" "N" "N" "Y"

這行得通嗎?

dat %>% mutate(z=ifelse(x=="Yellow" & y == "Yellow", "Y", "N"))

或者也許是這樣:

dat %>% mutate(z=ifelse(tolower(x)=="yellow" & tolower(y) == "yellow", "Y", "N"))

這是一個沒有ifelse的基本 R 選項

transform(
  df,
  z = c("N", "Y")[1 + (rowSums(cbind(x, y) == "Yellow") == 2)]
)

這使

  Id      x      y z
1 12 Yellow Yellow Y
2 13 Yellow   Blue N
3 10   Blue Yellow N
4 14   Blue   Blue N
5 19 Yellow Yellow Y

暫無
暫無

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

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