I have a table containing data that looks somewhat like this:
treatment, species1, species2, ...
A, 3, 4, ...
B, 2, 5, ...
I want to calculat
Depending on how your table is stored (this should work directly if it is the result of table
, but could need some tweaking if it is a data frame or other structure), but it could be as simple as:
newtable <- addmargins(mytable, 1, FUN = function(x) sum( x > 0 ) )
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)