[英]R: ifelse statement to assign a value to another column
Based on three conditions I want to assign the value 1. The following code works if I use only one &
(so for example leave out 2018).基于三个条件,我想分配值 1。如果我只使用一个
&
(例如,省略 2018),则以下代码有效。
df[df$2017 == 1 &
df$2018 == 0 &
df$x == -1, ]$y <- 1
I believe an ifelse statements is what I need, but I don't understand how to assign value 1
to column y
within the statement.我相信 ifelse 语句是我需要的,但我不明白如何将值
1
分配给语句中的y
列。
Help is much appreciated非常感谢帮助
It is better to subset the 'y' with the logical vector instead of subsettng the whole dataset and then extracting the column最好用逻辑向量对“y”进行子集化,而不是对整个数据集进行子集化然后提取列
df$y[with(df, `2017` == 1 &
`2018` == 0 &
x == -1)] <- 1
If we need to use multiple values, change the ==
to %in%
如果我们需要使用多个值,请将
==
更改为%in%
df$y[with(df, `2017` == 1 &
`2018` == 0 &
x == -1 &
`2019` %in% c(0, 1))] <- 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.