r - 有没有办法生成一个新变量,以 R Studio 中其他两个变量中的不同文本值为条件
问题描述
我正在寻找一个函数,它允许我根据其他两个变量中的文本值生成一个新变量。
变量x
具有文本值"both"
"current"
"no"
"previous"
,变量y
具有文本值"yes"
和"no"
.
现在我想创建一个z
具有文本值 yes 的变量,如果其他变量中的文本值是"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
推荐阅读
- javascript - 将 html 表附加到另一个表中
- python - AWS Access KEY,通过python脚本访问秘钥
- vue.js - 错误:vuex 不会在突变处理程序之外改变 vuex 存储状态即使将 const 传递给突变
- 3d - 如何确定 3D 坐标是否位于 BIM 中 3D 对象的边界内?我正在使用 Xbim 处理 IFC 文件
- reactjs - 在反应js和redux中从另一个类获取数据到主屏幕
- ios - 配置 AVAudioSession 会抛出错误?
- spring - 无法使用单向 @OneToMany 关系 JPA 获取记录
- javascript - HTML 视频缓冲冻结
- php - 我的登录页面将允许任何凭据登录
- r - 发生错误时如何退出R脚本