Вот начало, с data.table
, plyr
и базовыми функциями, есть так много других способов ...
Во-первых, некоторые примеры данных ...
dput(examp)
structure(list(P = structure(c(1L, 1L, 1L, 2L), .Label = c("P1",
"P2"), class = "factor"), M = structure(c(1L, 1L, 2L, 2L), .Label = c("M1",
"M2"), class = "factor"), R = structure(c(1L, 2L, 1L, 1L), .Label = c("R1",
"R2"), class = "factor"), V = c(23, 49, 24, 29)), .Names = c("P",
"M", "R", "V"), row.names = c(NA, -4L), class = "data.frame")
#
# to give something like what you have...
#
examp
P M R V
1 P1 M1 R1 23
2 P1 M1 R2 49
3 P1 M2 R1 24
4 P2 M2 R1 29
Вот один из способов использования data.table
.Если ваш объект данных очень большой, пакет data.table
окажется очень быстрым, документация также превосходна: http://datatable.r -forge.r-project.org / datatable-intro.pdf
# What is the average of each element of P?
library(data.table)
examp.dt <- data.table(examp)
setkey(examp.dt,P)
examp.dt[,mean(V),by=P]
P V1
[1,] P1 32
[2,] P2 29
#
И еще один, использующий plyr
# What is the average of each element of P?
library(plyr)
ddply(examp, "P", function(df)mean(df$V))
P V1
1 P1 32
2 P2 29
И еще один, использующий базу R
# What is the average of each element of P?
# for example using the by() function, tapply() would be similar
with(examp, by(examp, P, mean))
P: P1
P M R V
NA NA NA 32
-------------------------------------------------
P: P2
P M R V
NA NA NA 29
#
# What is the average of each element of R?
with(examp, by(examp, R, mean))
R: R1
P M R V
NA NA NA 25.33333
----------------------------------------------
R: R2
P M R V
NA NA NA 49
#
# the same, using tapply
with(examp, tapply(V, R, mean)
R1 R2
25.33333 49.00000
И, на ваш последний вопрос, сколько элементов P1больше определенного значения, мы можем использовать subset
, например, так:
# how many elements of P1 are greater than 20?
nrow(subset(examp, examp$P=="P1" & examp$V>20))
[1] 3
или даже просто [
для того же результата с меньшим набором:
nrow(examp[examp$P=="P1" & examp$V>20,])
[1] 3