Leosar
Leosar

Reputation: 2072

select subset of different data.frame columns

I want to select a different a subset of a dataframe from each column and do and average like this

per <- data.frame(Apocal=c(10,1,2,3,4,0,6),Aporos=c(0,2,1,3,0,5,6),Euker=c(0,3,5,7,0,0,0), fecha=c(1,1,2,2,2,3,3))

temp <-with(per, per[Apocal>0,])
require(plyr)
temp <- ddply(temp, .(fecha), summarise, Apocal = mean(Apocal))

temp <-with(per, per[Aporos>0,])
temp <- ddply(temp, .(fecha), summarise, Aporos = mean(Aporos))

...

And repeat for every column, except fecha, is there any way to automate this with a function or another thing?

Thanks!

Upvotes: 3

Views: 171

Answers (3)

Arun
Arun

Reputation: 118799

If your function is mean you can use the function colMeans normally. It computes mean of all columns (column-wise means). But since you require to compute the mean after removing each column's 0 entries, you can use colSums as follows:

# x gets all columns grouped by `fecha`.
ddply(per, .(fecha), function(x) colSums(x[, -4])/colSums(x[, -4] != 0))
#   fecha Apocal Aporos Euker
# 1     1    5.5    2.0     3
# 2     2    3.0    2.0     6
# 3     3    6.0    5.5   NaN

Upvotes: 1

vinux
vinux

Reputation: 965

pmean <- function(x,byvar){
  y=x[,-1*byvar]
  colSums(y*(y>0))/colSums(y>0)
}

ddply(per, .(fecha), function(x) pmean(x,4))

Modified version of Arun's soluton.

Upvotes: 1

flodel
flodel

Reputation: 89057

With aggregate:

aggregate(. ~ fecha, data = per, function(x)mean(x[x > 0]))
#   fecha Apocal Aporos Euker
# 1     1    5.5    2.0     3
# 2     2    3.0    2.0     6
# 3     3    6.0    5.5   NaN

Upvotes: 3

Related Questions