1

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

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

它们是 和 的平均值,value1以及和value2Year1平均值。谢谢!value15Year2

4

2 回答 2

3

这是一种使用基函数的方法。我猜 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
于 2013-05-09T23:17:32.823 回答
1

这是使用的版本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
于 2013-05-09T23:43:42.627 回答