繁体   English   中英

根据R中的条件查询和汇总数据

[英]Query and aggregate data based on conditions in R

我有一个数据框,如果type a值等于1,我希望得到每年type b的所有值的均值。

Year  type   value1   value2  value3  value4  value5
1     a       1        1        2       3       4
1     b       10       12       9       8       10
2     a       1        2        2       2       1
2     b       11       10       13      9       14

所以我的最终产品看起来像这样:

Year  type_b_values
1      11
2      12.5

这是Year1value1value2的平均值,以及Year1value15Year2 谢谢!

这是一种使用基本函数的方法。 我猜plyr或reshape也可能是有用的包,但我对它们不太熟悉:

dat <- read.table(text="Year  type   value1   value2  value3  value4  value5
1     a       1        1        2       3       4
1     b       10       12       9       8       10
2     a       1        2        2       2       1
2     b       11       10       13      9       14", header=TRUE)


dat_split <- split(dat, dat$Year)       # split our data into a list by year

output <- sapply(dat_split, function(x) {
    y <- x[x$type == "a", -c(1:2)] == 1 # which a in that year = 1
    z <- x[x$type == "b", -c(1:2)][y]   # grab the b values that a = 1
    if (sum(y) == 0) {                  # eliminate if no a = 1
        return(NA)
    }
    mean(z)
})

data.frame(Year = names(output), type_b_values = output)

## > data.frame(Year = names(output), type_b_values = output)
##   Year type_b_values
## 1    1          11.0
## 2    2          12.5

这是使用plyr的版本:

library(plyr)
ddply(dat, "Year", function(x) {
  values.cols <- grep("value", names(x), value = TRUE)
  a <- subset(x, type == "a", values.cols)
  b <- subset(x, type == "b", values.cols)  
  c("type_b_values" = mean(b[a == 1]))
})

#   Year type_b_values
# 1    1          11.0
# 2    2          12.5

暂无
暂无

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

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