我在条件子集信息方面苦苦挣扎以平均子集
我有2个数据集:
type<-c("flesh","wholefish","wholefish","wholefishdelip")
group<-c("two","four",'five','five')
N<-c(10.2,11.1,10.7,11.3)
prey <- cbind(type,group,N)
sample<-c('plasma','wholeblood','redbloodcell')
group1<-c('four','four','two')
group2<-c('','five','four')
group3<-c('','','five')
avgN<-c("","","")
penguin<-cbind(sample,group1,group2,group3,avgN)
我想输出看起来像这样
sample | group1 | group2 | group3 | avgNwf
plasma | four | | | 11.1 #made up by (11.1/1)
wholeblood | four | five | | 10.9 #(11.1+10.7)/2
redbloodcell | two | four | five | 10.9 #(11.1+10.7)/2
我想根据每行的条件计算企鹅$ avgN的值。我想计算平均猎物$ N如果猎物$ Type ==&#34; wholefish&#34; &安培;猎物$ group匹配penguin $ group1,penguin $ group2和penguin $ group3。并非所有的企鹅组都有条目,所以我遇到了excel的问题,我无法忽略#N / A. (并且excel不具备条件标准偏差的功能)
企鹅数据帧中第一行的IE,我想要对第4组和第5组中的所有整鱼进行平均N(猎物df)。 我尝试了以下条件较少的条件只是为了看看我是否正常,但无济于事:
avgN <-mean(ifelse(prey$group==penguin$group1,prey$N, "nope"))
avgN <-mean(prey$N[prey$group==penguin$group1,])
以下不是我想要实现的目标:
avgN = summaryBy(N ~group+type, data=prey, FUN=c(mean, sd), na.rm=T)
因为它带回了信息的摘要版本,而不是每个条目的个别结果都有自己的条件。
avgN <-mean(prey$N)
因为它缺乏每个样品的条件。
在excel中,我会使用单元格引用来处理行中唯一的条件。
答案 0 :(得分:0)
所以,对于任何挣扎类似事情的人来说,这是一个答案
for(i in 1:3) {
#condition 1 prey$type=="wholefish"
a<- which(prey[,1]=="wholefish")
#condition 2 prey$group==penguin$group1
b<- which(prey[,2]==penguin[i,2])
c<-match(a,b)
d<-which(c>0)
ad<-a[d]
#condition 3 prey$group==penguin$group2
bb<- which(prey[,2]==penguin[i,3])
cc<-match(a,bb)
dd<-which(cc>0)
add<-a[dd]
#condition 4 prey$group==penguin$group4
bbb<- which(prey[,2]==penguin[i,4])
ccc<-match(a,bbb)
ddd<-which(ccc>0)
addd<-a[ddd]
#some objects returned interger(0) which meant the mean couldn't be calculated
#so I removed those
if (identical(add,integer(0))==TRUE) {relrows<-c(ad)
} else {relrows<-c(ad,add)}
if (identical(addd,integer(0))==TRUE) {relrows2<-c(relrows)
} else {relrows2<-c(relrows,addd)}
#turns out prey and penguin were matrices
#to ensure that only the values of prey$N are used
#I made a new object with just a string a numbers
as.numeric(prey[,3])->prey3
#then I could do the calculations I wanted
penguin[i,5]<-mean(prey3[relrows2])
penguin[i,6]<-sd(prey3[relrows2])
}
谢谢Z.Lin的帮助