Irina
Irina

Reputation: 21

R: count number of values per row in data set and create a new column

Thanks in advance. I need in a data frame count number of existing values (o,1,2) per row and create 3 columns for count number for each value I used the example:

example <- data.frame(var1 = c(2,3,3,2,4,5), 
              var2 = c(2,3,5,4,2,5), 
              var3 = c(3,3,4,3,4,5))
example <- cbind(example, apply(example, 1, function(x)length(unique(x))))

But it returns only number of unique values.

Upvotes: 2

Views: 103

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Is this what you want?

all_vals = unique(unlist(example))
tt = t(apply(example, 1, function(x) table(factor(x, levels = all_vals))))
cbind(example, tt)
#   var1 var2 var3 2 3 4 5
# 1    2    2    3 2 1 0 0
# 2    3    3    3 0 3 0 0
# 3    3    5    4 0 1 1 1
# 4    2    4    3 1 1 1 0
# 5    4    2    4 1 0 2 0
# 6    5    5    5 0 0 0 3

A good next step would be renaming the new columns.

Upvotes: 2

Related Questions