user3459293
user3459293

Reputation: 340

Calculate row means on specific columns

I have six replicates for each sample. I want to calculate mean of each sample_id for the column reading. I want to keep sample_id with mean of reading. the data looks like this;

Sample  Replicate   Number  Reading
S_1     1   1   7
S_1     2   2   7
S_1     3   1   7
S_1     4   2   9
S_1     5   1   9
S_1     6   2   7
S_2     1   1   6
S_2     2   2   6
S_2     3   1   9
S_2     4   2   9
S_2     5   1   9
S_2     6   2   9
S_3     1   1   1
S_4     2   2   1
S_5     3   1   1
S_6     4   2   1
S_7     5   1   2
S_8     6   2   1

So I should have

Sample Reading(mean)
S_1
S-2
..
S_8

Upvotes: 1

Views: 731

Answers (3)

Gavin Kelly
Gavin Kelly

Reputation: 2414

arr <- tapply(dframe$Reading, dframe$Sample, mean)

will give an array with means of Reading per Sample. If you want to create a data.frame of the result

tableFrame <- data.frame(Sample = names(arr), "Reading(mean)" = arr, check.names=FALSE)

Upvotes: 0

Maciej
Maciej

Reputation: 3303

You can use aggregate

aggregate(Reading~Sample,data=yourdata, mean)

Upvotes: 1

David Arenburg
David Arenburg

Reputation: 92292

test <- data.frame(Sample = c(rep("S_1", 6), rep("S_2", 6), "S_3", "S_4", "S_5", "S_6", "S_7", "S_8"),
                   Replicate = rep(1:6, 3))
aggregate(Replicate ~ Sample, test, mean)

Upvotes: 2

Related Questions