conditional count throughout each row using r

Viewed 58

I tried every solution but my problem is still there. I have a big df (20rows*400cols) - for each row I want to count how many columns have a value of more than 16.

The first col is factor and the rest of the columns are integers.

my df:

col1 col2 col3 col4
abc   2    16   17    
def   4    2    4     
geh   50   60   73 

desired output should be:

col1 col2 col3 col4 count
abc   2    16   17    1
def   4    2    4     0
geh   50   60   73    3

I tried df$morethan16 <- rowSums(df[,-1] > 16) but then I get NA in the count column.

2 Answers

We may need na.rm to take care of NA elements as >/</== returns NA wherever there are NA elements

df$morethan16 <- rowSums(df[,-1] > 16, na.rm = TRUE)

If we still get NA, check the class of the columns. The above code works only if the columns are numeric. Convert to numeric class automatically with type.convert (based on the values of the column)

df <- type.convert(df, as.is = TRUE)

check the structure

str(df)

If it is still not numeric, some values in the column may be character elements that prevents it from conversion to numeric. Force the columns to numeric with as.numeric. If those are factor columns, do as.character first

df[-1] <- lapply(df[-1], function(x) as.numeric(as.character(x)))

Here is another option using crossprod

df$count <- c(crossprod(rep(1, ncol(df[-1])), t(df[-1] > 16)))

which gives

  col1 col2 col3 col4 count
1  abc    2   16   17     1
2  def    4    2    4     0
3  geh   50   60   73     3
Related