5

嗨有经验的 R 用户,

这是一件很简单的事情。我想x根据Group.1一个可控变量求和。

当我说类似的话时,我想x通过对前两行进行分组来求和:number <- 2 如果我说3,它应该x对前三行求和Group.1

知道如何解决这个问题吗?我应该写一个函数吗?提前谢谢大家。

  Group.1  Group.2      x
1       1     Eggs 230299
2       2     Eggs 263066
3       3     Eggs 266504
4       4     Eggs 177196
4

5 回答 5

6

如果您想要的总和总是累积的,那么有一个函数可以做到这一点,cumsum. 它是这样工作的。

> cumsum(c(1,2,3))
[1] 1 3 6

在这种情况下,您可能想要类似的东西

> mysum <- cumsum(yourdata$x)
> mysum[2] # the sum of the first two rows
> mysum[3] # the sum of the first three rows
> mysum[number] # the sum of the first "number" rows
于 2013-11-06T22:33:48.610 回答
4

假设您的数据位于mydata

with(mydata, sum(x[Group.1 <= 2])
于 2013-11-06T20:35:44.600 回答
2

您可以使用该by功能。

例如,给定以下 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
于 2013-11-06T20:57:18.837 回答
1

如果您只想汇总数据的子集:

my_data <- data.frame(c("TRUE","FALSE","FALSE","FALSE","TRUE"), c(1,2,3,4,5))
names(my_data)[1] <- "DESCRIPTION" #Change Column Name
names(my_data)[2] <- "NUMBER"      #Change Column Name

sum(subset(my_data, my_data$DESCRIPTION=="TRUE")$NUMBER)

你应该得到6。

于 2019-10-25T12:24:14.857 回答
0

不知道为什么Eggs在这里很重要;)

df1 <- data.frame(Gr=seq(4),
                  x=c(230299, 263066, 266504, 177196)
                  )

现在有了n=2前两行:

n <- 2
sum(df1[, "x"][df1[, "Gr"]<=n]) 

该表达式[df1[, "Gr"]<=n]创建一个逻辑向量以在对元素进行分类df1[, "x"]之前sum对其进行子集化。

此外,看来您Group.1的行号与行号相同。如果是这样,这可能更简单:

sum(df1[, "x"][1:n])

或一次得到所有

cumsum(df1[, "x"])
于 2013-11-06T22:45:04.820 回答