How to add a column giving the number of values >0 in each row to a table in R?

后端 未结 2 1026
广开言路
广开言路 2021-01-25 02:52

I have a table containing data that looks somewhat like this:

treatment, species1, species2, ... 
A, 3, 4, ... 
B, 2, 5, ...

I want to calculat

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 03:17

    Try something like this. It might take some tweaking to fit your data (it helps to provide some sample data with your question), but this should get you most of the way there.

    # An easy way to make sample data
    dat <- data.frame(treatment = letters[1:5],
                      species1 = c(3, 4, 0, 1, 3),
                      species2 = c(2, 1, 0, 0, 7),
                      species3 = c(0, 4, 0, 1, 0))
    
    # First step: dat[ , -1] > 0 indicates which values are greater than zero
    # You want to exclude the first column, since that just indicates 
    # treatment group
    dat[ , -1] > 0
    
    # rowSums counts the number of values > 0 in each row - that's because, in R,
    # you can add TRUE values to count them
    rowSums(dat[ , -1] > 0)
    
    # Finally, wrap it all up and add it to your data.frame
    dat$number_of_species <- rowSums(dat[ , -1] > 0)
    

提交回复
热议问题