如何使用循环和ifelse语句创建新变量 [英] How to create new variables using loop and ifelse statement
问题描述
我有许多名称相同但后缀不同的变量.例如,var1,var2,var3,var4,var5,var6,...等.这些变量中的每一个都有一个随机序列,分别为0、1和2.使用这些变量,我试图创建一个名为testvariable
的新变量.如果任何现有变量具有1,则将testvariable
设置为1.如果它们具有0或2,则将分配0.
I have a number of variables with the same name but different suffixes. For example, var1, var2, var3, var4, var5, var6, ... and so on. Each of these variables has a random sequence of 0, 1, and 2. Using these variables, I am trying to create a new variable called testvariable
. If any of the already existing variables has 1, I will set testvariable
to 1. If they have 0 or 2, I will assign 0.
是否可以使用一个简单的循环和/或ifelse语句来创建此变量?我的真实数据要比这复杂得多,所以我不想复制并粘贴每个单独的变量和值.
Is there a simple loop and/or ifelse statement I can use to create this variable? My real data is a lot more complex than this, so I don't want to copy and paste each individual variable and values.
这是针对R.
推荐答案
如果我正确理解你的话,如果任何变量(如var1,var2,..等)的值为1,则testvariable必须为1,否则为0 ,然后执行:
If I understand you correctly, if any of the variables like var1, var2, .., etc has a value 1, then the testvariable must be 1 else 0, then do:
样本df:
var1 var2 var3 var4 var5
1 1 1 1 1 1
2 2 2 2 2 2
3 0 1 0 1 0
4 0 0 0 0 1
5 1 1 2 1 2
6 2 2 2 2 2
7 2 2 1 2 2
8 1 1 2 1 1
9 0 0 0 0 0
代码:
df$testvariable <- ifelse(rowSums(df[, grepl("var", names(df))] == 1) > 0, 1, 0)
输出:
var1 var2 var3 var4 var5 testvariable
1 1 1 1 1 1 1
2 2 2 2 2 2 0
3 0 1 0 1 0 1
4 0 0 0 0 1 1
5 1 1 2 1 2 1
6 2 2 2 2 2 0
7 2 2 1 2 2 1
8 1 1 2 1 1 1
9 0 0 0 0 0 0
这篇关于如何使用循环和ifelse语句创建新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!