代码之家  ›  专栏  ›  技术社区  ›  Lyndz

列中唯一值的总和

  •  0
  • Lyndz  · 技术社区  · 7 年前

    我想在满足某些条件后,每年在列中获得唯一值的总和。

    以下是我从DPUT获得的数据:

    structure(list(key = structure(c(1L, 1L, 4L, 2L, 3L, 4L, 2L, 
    3L, 5L, 5L, 8L, 6L, 7L, 8L, 6L, 7L), .Label = c("1992_10_18_0", 
    "1992_10_18_12", "1992_10_18_18", "1992_10_18_6", "1993_10_18_0", 
    "1993_10_18_12", "1993_10_18_18", "1993_10_18_6"), class = "factor"), 
     RR = c(43.25, 43.25, 43.25, 43.25, 43.25, 43.25, 43.25, 43.25, 
     43.25, 43.25, 43.25, 43.25, 43.25, 43.25, 43.25, 43.25), 
     dist = c(1000.23361607017, 694.022935174544, 748.618896699399, 
     812.290633745208, 869.896619169459, 1136.88564181537, 
     1058.59136791648, 
     975.756885299645, 1000.23361607017, 694.022935174544, 
     748.618896699399, 
     812.290633745208, 869.896619169459, 1136.88564181537, 
     1058.59136791648, 
     975.756885299645), Year = c(1992L, 1992L, 1992L, 1992L, 1992L, 
     1992L, 1992L, 1992L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 
    1993L, 1993L)), class = "data.frame", row.names = c(NA, -16L
    ))
    

    我想要的:

    数据中有四列:key、rr、dist和year。

    我想根据每年唯一的“关键”值得到RR的总和,这样“dist”就小于或等于1100。

    到目前为止我有:

    我正在处理多个文件,因此脚本如下:

    dat<-read.csv("test_dat.csv",header=T,stringsAsFactors=FALSE)
    
    dat2<-dat[which(dat$dist <= 1100),]
    dat3<-as.data.frame(cbind(dat2$RR,dat2$Year))
    colnames(dat3)<-c("RR","Year")
    agg<-aggregate(.~Year,dat3,sum,na.rm=T)
    
    write.csv(agg,file="test.csv",row.names=T)
    

    我能在R里怎么做吗? 我会感谢你的帮助。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Ronak Shah    7 年前

    dplyr filter dist key sum RR 距离

    library(dplyr)
    
    df %>%
      group_by(Year) %>%
      filter(dist <= 1100 & !duplicated(key)) %>%
      summarise(RR = sum(RR), dist = sum(dist))
    

    n_distinct

    df %>%
      filter(dist <= 1100) %>%
      group_by(Year) %>%
      summarise(n = n_distinct(key))
    
        2
  •  1
  •   DMR    7 年前

    aggregate unique

    agg <- aggregate(key ~ Year, data=subset(dat, dist <= 1100), FUN=function(x) length(unique(x)))
    

    dat<-read.csv("test_dat.csv",header=T,stringsAsFactors=FALSE)
    agg <- aggregate(key ~ Year, data=subset(dat, dist <= 1100), FUN=function(x) length(unique(x)))
    write.csv(agg,file="test.csv",row.names=T)
    

    在本例中,生成的输出为:

      Year key
    1 1992   4
    2 1993   4