user1308144
user1308144

Reputation: 475

Evaluate data frame column by column and replace every value in that column depending on meeting a condition

I have a data frame (df) like this:

0 5 5 5 5 5
0 5 5 5 0 5
0 5 5 5 NA 5
5 0 0 0 NA 5

and I want to check each column in turn and count the number of rows with a value greater than 0. If the number of rows with values greater than 0 is more than 3 I want to replace all values in that column with NA. The output for the above would look like this:

0 5 5 5 5 NA
0 5 5 5 0 NA
0 5 5 5 NA NA
5 0 0 0 NA NA

This is what I have tried

df[,(nrow(df)>0)> 3]<-NA

Upvotes: 0

Views: 59

Answers (1)

amatsuo_net
amatsuo_net

Reputation: 2448

This is the solution:

df[, colSums(df > 0)> 3]<-NA

Upvotes: 1

Related Questions