将函数应用于拆分数据框的所有子集上的一列

时间:2014-01-26 16:06:21

标签: r function split apply

我根据一列连续数据的一系列子间隔分割了我的数据帧:

Data1 <- read.csv(file.choose(), header = T)

# Order (ascending)by size
Group.order <- order(GroupN)

# Assign label to data frame ordered by group
Data1.group.order <- Data1[Group.order, ]

# Set a range of sub-intervals we wish to split the ordered data into
range <- seq(0, 300, by=75)

# Use the split function to split the ordered data, using the cut function which will           
# cut the numeric vector GroupN by the value 'range'
Split.Data1 <- split(Data1.group.order, cut(Data1.group.order$GroupN, range))

随着数据的分割,我现在需要找到数据框所有子集中其中一列的平均值,但尽管我付出了很多努力,但仍在努力。

但是,我已经能够使用lapply函数找到整个拆分数据框中多列的平均值,但不能单独找到一列。

任何帮助将不胜感激。

编辑:我是R新手,所以我真正想做的是查看数据框的每个子集的变量x的分布,即x轴= 0-75,75-150,150 -225,225-300,y轴=变量x。我的计划是分割数据,找到数据帧的每个子集的变量x的平均值,然后按照数据帧的子集I的间隔绘制变量x。但是,我确信有更好的方法可以做到这一点!

1 个答案:

答案 0 :(得分:1)

使用plyr

这样的事情怎么样?
require(plyr) # library

dat<-data.frame(x=sample(1:300,300),y=runif(300)*10)   # create random data
head(dat)

#    x        y
#1 193 2.580328
#2 119 4.519489
#3  51 5.340437
#4 114 9.249253
#5 236 4.756849
#6 108 5.926478

ddply(dat,                                                 # use dat
      .(grp=cut(dat$x,seq(0,300,75),seq(0,300,75)[-1])),   # group by formula (cut)
      summarise,                                           # tell ddply to summarise
      mean=mean(y),                                        # calc mean
      sum=sum(y))                                          # calc sum

#  grp     mean      sum
#1  75 4.620653 346.5490
#2 150 5.337813 400.3360
#3 225 4.238518 317.8889
#4 300 4.996709 374.7532