有没有办法生成一个新变量,以 R Studio 中其他两个变量的不同文本值为条件

Is there a way to produce a new variable, conditioned on different text values in two other variables in R Studio

我正在寻找一个函数,它允许我根据另外两个变量中的文本值生成一个新变量。

变量 x 具有文本值 "both" "current" "no" "previous" 变量 y 具有文本值 "yes""no"

现在我想创建一个文本值为 yes 的变量 z,如果其他变量中的文本值为 "both" "current" "previous""yes"(所以除 "no" 以外的所有内容)。

是否存在这样的函数,我相信它存在,但我已经挖掘了几个小时也没有找到任何合适的东西。

感谢任何帮助 - 我是论坛的新手,很抱歉无法提供数据示例,我的数据集太大了。

这适合你的情况吗?

# exemple data with all the cases possible.
df<- data.frame(x = rep(c('both','current','no','previous'),2),
                y = c(rep('yes',4),rep('no',4)), stringsAsFactors = FALSE)
df
#          x   y
# 1     both yes
# 2  current yes
# 3       no yes
# 4 previous yes
# 5     both  no
# 6  current  no
# 7       no  no
# 8 previous  no
#### EDIT ####
# new method corrected via the comments
df$z <- rep('yes',nrow(df))
df$z[df$x == 'no' & df$y == 'no'] <- 'no'
#          x   y   z
# 1     both yes yes
# 2  current yes yes
# 3       no yes yes
# 4 previous yes yes
# 5     both  no yes
# 6  current  no yes
# 7       no  no  no
# 8 previous  no yes

# Old method
# Here I change every row of df$z where df$x is not 'no' and df$y is not 'no'
df$z[df$x != 'no' & df$y != 'no'] <-df$x[df$x != 'no' & df$y != 'no']
# Here I change every row of df$z where df$y is not 'no'. Not sure is this is in your question.
df$z[df$y != 'no'] <-df$y[df$y != 'no']
df