Reputation: 13
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!
Thanks in advance, Peter
Upvotes: 1
Views: 161
Reputation: 49640
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 ) )
Upvotes: 0
Reputation: 27349
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)
Upvotes: 4