Reputation: 331
How do I create an additional column which assigns a factor based on whether the row meets 1 of 3 conditions?
In the example, I want the column to assign a 1 if only an entry for a exists, a 2 if an entry for a and b exists, and a 3 if a row has an entry for a,b and c.
before <- data.frame(
a = c(1,3,2,2,4),
b = c(NA,2,3,NA,3),
c = c(NA,NA,NA,NA,5)
)
after <- data.frame(
a = c(1,3,2,2,4),
b = c(NA,2,3,NA,3),
c = c(NA,NA,NA,NA,5),
level = c(1,2,2,1,3)
)
Upvotes: 1
Views: 35
Reputation: 39717
You can use is.na
and rowSums
to count how many entry's exists per row.
before$level <- rowSums(!is.na(before))
before
# a b c level
#1 1 NA NA 1
#2 3 2 NA 2
#3 2 3 NA 2
#4 2 NA NA 1
#5 4 3 5 3
Upvotes: 2