【问题标题】:Counting the NUM of rows that contains a certain year计算包含特定年份的行数
【发布时间】:2017-11-12 11:01:20
【问题描述】:

我有一个包含这种格式的日期列的数据框 (1990-02-28) 我想计算包含 1996 年的行数(与月/日无关)。

例如:

DF

1. 1946-01-21   -0.7062
2. 1986-01-22   0.5029
3. 1923-01-23   0.5657
4. 1920-01-25   0.4723
5. 1996-01-26   -0.5384
6. 1996-01-27   0.717

响应为 2(对于 #5、#6)

谢谢

【问题讨论】:

    标签: r dataframe rowcount


    【解决方案1】:
    library(lubridate)
    library(dplyr)
    
    dt = read.table(text = "
    date value
    19460121 -0.7062
    19860122 0.5029
    19230123 0.5657
    19200125 0.4723
    19960126 -0.5384
    19960127 0.717
    ", header = T)
    
    dt %>%
      mutate(date = ymd(date)) %>%     # make this a date column (if it's not already) 
      filter(year(date) == 1996) %>%   # filter rows where the year is 1996
      nrow()                           # count rows
    

    【讨论】:

    • 我得到这个响应:{年份错误(COMBINED$TrdDate):找不到函数“year”},我也试过了,sum(years(as.Date(COMBINED$TrdDate))= =“1996”,na.rm = 真)。其中 COMBINED 是我的 DataFrame,TrdDate 是我的日期列,谢谢
    • 您确定您使用的是lubridate 包吗?确保首先使用 install.packages("lubridate") 安装它。
    • 我不认为您使用的years 命令符合您的想法。
    • 还是无法识别函数“year”。
    • 你使用的其他包一定有冲突。尝试以这种方式使用函数lubridate::year
    【解决方案2】:

    与基础 R 的其他方式:

    df=read.table(text="
    19460121 -0.7062
    19860122 0.5029
    19230123 0.5657
    19200125 0.4723
    19960126 -0.5384
    19960127 0.717")
    
    df$V1=as.character(df$V1)
    
    table(format(as.Date(df$V1,"%Y%m%d"),"%Y"))
    #1920 1923 1946 1986 1996 
    #   1    1    1    1    2 
    
    table(format(as.Date(df$V1,"%Y%m%d"),"%Y"))["1996"]
    #1996 
    #   2
    

    【讨论】:

    • 谢谢罗伯特,我成功了。
    【解决方案3】:

    仅列操作可能会更快。以下是其中的 3 个:

    read.table(stringsAsFactors=FALSE, header=FALSE, text="
    19460121 -0.7062
    19860122 0.5029
    19230123 0.5657
    19200125 0.4723
    19960126 -0.5384
    19960127 0.717") -> xdf
    
    # base R
    sum(grepl("^1996", xdf$V1))
    
    # stringi one way
    sum(!is.na(stringi::stri_match_first_regex(xdf$V1, "^1996")))
    
    # stringi another way
    sum(stringi::stri_count_regex(xdf$V1, "^1996"))
    

    【讨论】:

      【解决方案4】:

      在基础 R 中声明

      DF[ grepl( "1996", DF[ , 1 ] ), ]
      

      会实现你的目标:

      > DF[ grepl( "1996", DF[ , 1 ] ), ]
            date   value
      5 19960126 -0.5384
      6 19960127  0.7170
      

      编辑:

      行数可以用

      找到
      nrow( DF[ grepl( "1996", DF[ , 1 ] ), ] )
      

      或正确使用length()

      length( DF[ grepl( "1996", DF[ , 1 ] ), 1 ] )
      

      【讨论】:

      • 感谢您的响应,因为我需要该命令仅执行行数,而没有更多输出。关于我给出的例子,输出应该是2。
      • @EliadHarell,如果您在发布到 SO 时学会了一点 R,那将会有所帮助。你真的不能把nrow() 包裹在@vaettchen 的答案周围吗?
      • length() 提供列数@vaettchen,而不是# 行
      猜你喜欢
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      相关资源
      最近更新 更多