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

问题描述

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

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

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

这样的功能是否存在,我相信它确实存在,但是我挖了几个小时却没有找到任何合适的东西。

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

标签: rvariablesrstudio

解决方案


这适合你的情况吗?

# 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

推荐阅读