Reputation: 23
I am new to R. Tried searching for the answer but haven't got it as yet.I am sorry if somebody has already asked it.
Name1 Name2 Name3 Count_Var
A B C 3
D E F 3
G H 2
I 1
J K 2
L M 2
N O 2
I have three variables Name1,Name2 and Name3 in my dataframe. I want to introduce another variable i.e. count_var which would be the count of elements of Name1, Name2 & Name3.
Any help in this regard would be appreciated.
Upvotes: 0
Views: 65
Reputation: 270
Simple solution can be:
df$Count_Var = apply(df, 1, function(x) length(which(x==1)))
Upvotes: 0
Reputation: 886938
We can use rowSums
on a logical matrix i.e. create one where there are no blank elements (assumed that it is ""
for blank)
df1$Count_Var <- rowSums(df1[1:3]!="")
df1$Count_Var
#[1] 3 3 2 1 2 2 2
Upvotes: 1