[英]Applying a function to one column over all subsets of a split dataframe
我已經根據一列連續數據的子間隔范圍划分了數據框:
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。 但是,我敢肯定有更好的方法!
與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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.