【问题标题】:Filter by rows and sum column values按行过滤并对列值求和
【发布时间】:2017-10-13 07:17:05
【问题描述】:

我的数据看起来像

pos year A   B
1   2012 1   1
1   2013 1   NA
2   2012 NA  NA
2   2013 NA  1

仅当 A 和 B 都不是 NA 时,我才尝试计算每个 pos 的 A 和 B 之间的百分比差异。

ddply(x, .(pos), summarize, diff = ifelse(is.na(A)==FALSE & is.na(B)==FALSE, 
                                      (rowsum(A, pos, na.rm=TRUE)-rowsum(B, pos, na.rm=TRUE))/rowsum(A, pos, na.rm=TRUE),""))

所以结果应该是

pos diff
1   0.5
2   NA

我不知道哪一部分错了,但我的代码产生了

pos diff
1   0.5
1     
2     
2  

任何想法将不胜感激。谢谢!

【问题讨论】:

  • 这是你想要的吗'd %>% filter(!(is.na(A) & is.na(B))) %>% group_by(pos) %>% mutate(A1=sum(A,na.rm = T), A2=sum(B, na.rm = T)) %>% mutate(Dif=A1-A2, res=Dif/A1)
  • 嗨。感谢过滤器部分。但是 rowsum 函数很适合我的情况。

标签: r dplyr plyr rowsum


【解决方案1】:

不是最优雅的代码,但它似乎可以工作:

df <- data.frame(pos = rep(1:2, each = 2), year = rep(2012:2013, 2),
                 A = rep(c(1, NA), each = 2), B = c(1, NA, NA, 1))

foo <- function(x) ifelse(
  all(is.na(x[[1]])) | all(is.na(x[[2]])),
  NA, (sum(x[[1]], na.rm = T) - sum(x[[2]], na.rm = T)) / nrow(x))
x <- by(df[ , 3:4], df$pos, foo)
data.frame(pos = unique(df$pos), diff = as.vector(x))

   pos diff
    1  0.5
    2   NA

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2019-04-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多