本文介绍了在 R 中,如何将数据帧的某些行与某些逻辑相加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好有经验的 R 用户,
Hi experienced R users,
这是一件很简单的事情.我想根据一个可控变量对 x
和 Group.1
求和.
It's kind of a simple thing. I want to sum x
by Group.1
depending on one controllable variable.
当我说以下内容时,我想通过对前两行进行分组来对 x
求和:number <- 2
如果我说 3
,它应该将前三行的 x
与 Group.1
I'd like to sum x
by grouping the first two rows when I say something like: number <- 2
If I say 3
, it should sum x
of the first three rows by Group.1
知道如何解决这个问题吗?我应该写一个函数吗?提前谢谢大家.
Any idea how I might tackle this problem? Should I write a function? Thank y'all in advance.
Group.1 Group.2 x
1 1 Eggs 230299
2 2 Eggs 263066
3 3 Eggs 266504
4 4 Eggs 177196
推荐答案
您可以使用 by
函数.
例如,给定以下 data.frame:
For instance, given the following data.frame:
d <- data.frame(Group.1=c(1,1,2,1,3,3,1,3),Group.2=c('Eggs'),x=1:8)
> d
Group.1 Group.2 x
1 1 Eggs 1
2 1 Eggs 2
3 2 Eggs 3
4 1 Eggs 4
5 3 Eggs 5
6 3 Eggs 6
7 1 Eggs 7
8 3 Eggs 8
你可以这样做:
num <- 3 # sum only the first 3 rows
# The aggregation function:
# it is called for each group receiving the
# data.frame subset as input and returns the aggregated row
innerFunc <- function(subDf){
# we create the aggregated row by taking the first row of the subset
row <- head(subDf,1)
# we set the x column in the result row to the sum of the first "num"
# elements of the subset
row$x <- sum(head(subDf$x,num))
return(row)
}
# Here we call the "by" function:
# it returns an object of class "by" that is a list of the resulting
# aggregated rows; we want to convert it to a data.frame, so we call
# rbind repeatedly by using "do.call(rbind, ... )"
d2 <- do.call(rbind,by(data=d,INDICES=d$Group.1,FUN=innerFunc))
> d2
Group.1 Group.2 x
1 1 Eggs 7
2 2 Eggs 3
3 3 Eggs 19
这篇关于在 R 中,如何将数据帧的某些行与某些逻辑相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!