user553480
user553480

Reputation: 331

Assign factor for row that meets condition in R

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

Answers (1)

GKi
GKi

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

Related Questions