refroll
refroll

Reputation: 131

Specific aggregation of values in rows of a dataframe in R

It seems a very easy task, but I am looking for a smart solution to calculate the column aggr based on the values of the four other columns (a, b, c, d) within the same row of a data frame.

See example below:

df <- data.frame(a=c(1,1,1,1,1),
                 b=c(1,2,1,3,2), 
                 d=c(1,2,3,3,3), 
                 e=c(2,2,3,3,2), 
                 aggr=c(1,2,1,3,2))

The special conditions are:

Upvotes: 1

Views: 97

Answers (1)

Whitebeard
Whitebeard

Reputation: 6203

df <- data.frame(a=c(1,1,1,1,1),
             b=c(1,2,1,3,2), 
             d=c(1,2,3,3,3), 
             e=c(2,2,3,3,2))

df$aggr <- 1 + (rowSums(df == 3 | df == 2) > 2) + (rowSums(df == 3) > 2)
df
  a b d e aggr
1 1 1 1 2    1
2 1 2 2 2    2
3 1 1 3 3    1
4 1 3 3 3    3
5 1 2 3 2    2

Upvotes: 1

Related Questions