在R中创建一个具有独家条件的变量
我的数据看起来像这样
Q3A1<-c(0,1,0,1,1,1,0,1,0,1)
Q3A2<-c(0,1,1,1,0,1,0,0,0,1)
Q3A3<-c(1,1,0,1,0,1,0,0,0,1)
,我想创建一个新的变量Q3L,如果将Q1A1,Q1A2和Q1A3编码为1,
我尝试过的是1
dataQ$Q3L <- ifelse(dataQ$Q3A1==1|dataQ$Q3A2==1|dataQ$Q3A3==1, 1, 0 )
,但它似乎是在重新编码,因为至少三个等于1,但是我需要它们的树等于1,
我尝试了这一点,
library(dplyr)
dataQ %>%
mutate(Q3L = case_when(Q3A1 == 1 & Q3A2 == 1 & Q3A3 == 1 ~ 1,))
也不是成功
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我们可以在列名中使用
if_all
- 在start_with
'q3a'的列中循环,创建逻辑条件以检查列值是否为1()。 x == 1
),if_all
返回true
仅在一行的所有列都是true的情况下,即全部1,然后强迫逻辑(>
)是/false
),用+
或as.integer
注意:使用
|
或&amp;
>在可变数量的列数上可能很麻烦,而是使用
if_all
或使用rowsums
dataWe can use
if_all
- by looping over the columns thatstarts_with
'Q3A' in column names, create a logical condition to check whether the column values are 1 (.x == 1
),if_all
returnsTRUE
only when all of the columns for a row are TRUE i.e. all 1, then coerce the logical (TRUE/FALSE
) to binary with+
oras.integer
NOTE: Using
|
or&
on a variable number of columns can be cumbersome, instead using eitherif_all
or create the logical withrowSums
data
更新:感谢@LMC的输入:一种更具概括的方法是:
第一个答案:
我们可以使用
rowsums
并应用ifelse
语句:Update: thanks to input from @LMc: a more generalizable way would be:
First answer:
We could check with
rowSums
and apply anifelse
statement:您可以这样做:
输出:
You can do this:
Output:
或使用
purrr :: pmap_dbl
或
purrr ::降低
utput> output>
它的工作原理
两个答案都同样有效。他们逐行,将行转换为逻辑向量。
所有
然后测试行逻辑向量的每个元素是true
。如果是1
将返回,否则0
。purrr :: dred
的工作方式有所不同。对于每一行,它都使用&amp;
函数将行矢量降低到单个逻辑值中。Or with
purrr::pmap_dbl
Or
purrr::reduce
Output
How it works
Both answers work similarly. They go row-by-row and convert the rows to logical vectors.
all
then tests if every element of the row-wise logical vector isTRUE
. If it is then1
is returned otherwise0
.purrr::reduce
works a bit differently. For each row it reduces the row-wise vector using the&
function into a single logical value.