简体   繁体   English

如何将每行中值> 0的列添加到R中的表中?

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

I have a table containing data that looks somewhat like this: 我有一个包含看起来像这样的数据的表:

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

I want to calculate the number of species per row and add the numbers calculated as a new column to the table, to make it look like this: 我想计算每行的物种数量,并将计算为新列的数字添加到表中,使其看起来像这样:

treatment, species1, species2, ... , number_of_species
A,         3,        4,        ... , 6
B,         2,        5,        ... , 9

I hope you understand what I aim at. 我希望你明白我的目标。 As I'm new to R, I tried for some time and didn't find out, so help would be appreciated! 由于我是R的新手,我试了一段时间并没有发现,所以请帮助我们!

Thanks in advance, Peter 彼得,先谢谢你

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)

根据表的存储方式(如果它是table的结果,这应该直接工作,但如果是数据框或其他结构则需要进行一些调整),但它可以很简单:

newtable <- addmargins(mytable, 1, FUN = function(x) sum( x > 0 ) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM