简体   繁体   English

给定特定条件的列元素求和

[英]summing elements of a column given certain conditions

given a data.frame with 3 columns, I need to sum those elements belonging to the column III, given two conditions: column I and column II must have the same value (by row). 给定一个具有3列的data.frame ,给定两个条件,我需要对属于列III的那些元素求和:列I和列II必须具有相同的值(按行)。 For example, if I have this data.frame: 例如,如果我有此data.frame:

I . 一世 。 II . 二。 III 三级

1 2 0.3 1 2 0.3

1 2 0.4 1 2 0.4

2 1 0.3 2 1 0.3

2 3 0.5 2 3 0.5

3 1 0.5 3 1 0.5

I want to sum all values in III given I=1 with II=2; 我想在给定I = 1和II = 2的情况下求和III中的所有值; I=2 with II=1; I = 2,II = 1; I=2 with II=3 I = 2,II = 3

If you can convert the matrix to data.frame 如果可以将矩阵转换为data.frame

Using @Franks' dataset 使用@Franks的数据集

d1 <- as.data.frame(d)
library(dplyr)
d1%>% 
group_by(`I`, `II`) %>% 
summarize(Sum=sum(`III`))
#     Source: local data frame [4 x 3]
#  Groups: I

#   I II Sum
# 1 1  2 0.7
# 2 2  1 0.3
# 3 2  3 0.5
# 4 3  1 0.5

Turning @beginneR's comment into an answer, if your data frame is df : 如果您的数据框为df ,则将@beginneR的注释转换为答案:

aggregate(III ~ I + II, df, sum)
##   I II III
## 1 2  1 0.3
## 2 3  1 0.5
## 3 1  2 0.7
## 4 2  3 0.5

This will calculate the sum of the elements in column III for every combination of values in columns I and II . 这将为III列中值的每种组合计算III列中元素的总和。

Your question is a bit confusing because you refer to a 3 column data frame and then a 5X5 matrix. 您的问题有点令人困惑,因为您引用的是3列数据帧,然后是5X5矩阵。 A matrix is not the same as a data frame. 矩阵与数据帧不同。

# Read in sample matrix (3 columns, 5 rows)
d<-as.matrix(read.table(text="
I II III
1 2 0.3
1 2 0.4
2 1 0.3
2 3 0.5
3 1 0.5", header=T))

# get all sums by unique groupings of column I and II
all_group_sums <- tapply(d[,'III'], paste0(d[,'I'], d[,'II']), sum)

# conditions you're interested in
of_interest <- c("12", "21", "23")

# filter tapply result by conditions of interest
all_group_sums[of_interest]

# 12  21  23 
#0.7 0.3 0.5 

Or the same as above, just in one line: 或与上面相同,只是一行:

tapply(d[,'III'], paste0(d[,'I'], d[,'II']), sum)[c("12", "21", "23")]
# 12  21  23 
#0.7 0.3 0.5 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM