Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tapply() function dependent on multiple columns in R

In R, I have a table with Location, sample_year and count. So,

Location sample_year count  
A        1995        1
A        1995        1  
A        2000        3  
B        2000        1  
B        2000        1  
B        2000        5

I want a summary table that examines both the 'Location' and 'sample_year' columns and sums 'count' dependent on this unique combination instead of just a single column. So, end result should be:

Location sample_year sum_count
A        1995        2
A        2000        3
B        2000        7

I could merge columns and data into a new column to create unique a Location-sample_year but this is not a clean solution, esp if I need to scale it up to three columns at some point. There must be a better approach.

like image 548
DeLongTime Avatar asked Mar 07 '11 05:03

DeLongTime


People also ask

How would you use the Tapply () function in R?

tapply in R. Apply a function to each cell of a ragged array, that is to each (non-empty) group of values given by a unique combination of the levels of certain factors. Basically, tapply() applies a function or operation on subset of the vector broken down by a given factor variable.

How do I remove Na from tapply?

Suppose that your data frame contains some NA values in its columns. Within the tapply function you can specify additional arguments of the function you are applying, after the FUN argument. In this case, the mean function allows you to specify the na. rm argument to remove NA values.


1 Answers

You can use aggregate with a formula.

First the data:

x <- read.table(textConnection("Location sample_year count  
A        1995        1
A        1995        1  
A        2000        3  
B        2000        1  
B        2000        1  
B        2000        5"), header = TRUE)

Aggregate using sum with a formula specifying the grouping:

aggregate(count ~ Location+sample_year, data = x, sum)
    Location sample_year count
1        A        1995     2
2        A        2000     3
3        B        2000     7
like image 177
mdsumner Avatar answered Sep 23 '22 00:09

mdsumner