Volker Holzendorf
Volker Holzendorf

Reputation: 247

Creating an Indexvariable in R based on several Indexvariables

I'm looking for a fast and easy alternative in R to create new Indexvariables out of several existing Indexvariables. Eg:

var1 var2 var3 newvar
0    1    1    1
0    0    0    0
1    0    0    1
1    1    1    1
1    0    9    1
1    9    9    1
0    9    9    1

How to create the newvar column with only one line in R? I have also the value 9 for "not answered" in the dataframe. I Just want to count the values 1 (and nothing else).

I'm looking for an alternative for the SPSS-Code:

COMPUTE newvar= any(1,var1,var2,var3).

Upvotes: 0

Views: 53

Answers (2)

jogo
jogo

Reputation: 12559

To count the values 1 for each row you can just use:

mydf$newvar <- rowSums(mydf==1)

If you want to see whether any of the values is 1 (as your intended outpur newvar implies):

mydf$newvar <- +(rowSums(mydf==1)>0)

Upvotes: 1

Volker Holzendorf
Volker Holzendorf

Reputation: 247

Thank you Henrik! You are right. It was answered in the thread you mentioned. Here the answer again, because nothing is trivial for everyone :-)

newvar<-as.numeric(apply(cbind(var1,var2,var3), 1, function(r) any(r == 1)))

Elch von Oslo

Upvotes: 0

Related Questions