【问题标题】:Data Table Solution To New Structured Variable新结构化变量的数据表解决方案
【发布时间】:2020-02-24 14:51:45
【问题描述】:
data=data.frame("student"=c(1,1,1,1,2,2,2,2,3,3,4,4,4,4),
"score"=c(1,2,1,1,2,3,2,NA,3,NA,1,3,2,1),
"drop"=c(0,0,0,0,0,0,0,1,0,1,0,0,0,0),
"WANT"=c(1,2,1,1,2,3,3,4,3,4,1,3,3,3))

我有没有“WANT”的数据框“数据”,这是我希望使用 data.table 解决方案创建的。

规则是:

如果 score = 1, WANT = 1 如果 score = 2, WANT = 2 如果 score = 3, WANT = 3, 如果 drop = 1, WANT=4

如果在 t = 2 时得分并且在 t+1 = 1 时得分,那没关系,但是

如果 t = 3 的得分和任何以后的得分都小于 3,则将它们替换 3.

这意味着一个分数系列:1-2-1-3-1 should be: 1-2-1-3-3

    data2=data.frame("student"=c(1,1,1,1,2,2,2,2,3,3,4,4,4,4,5,5,5,5),
"score"=c(1,2,1,1,2,3,2,NA,3,NA,1,3,2,1,1,3,NA,2),
"drop"=c(0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0),
"WANT"=c(1,2,1,1,2,3,3,4,3,4,1,3,3,3,1,3,3,3))

【问题讨论】:

    标签: r dplyr data.table


    【解决方案1】:

    我们可以在根据每个“学生”的“分数”中出现 3 个值创建条件后使用replace

    library(dplyr)
    data %>% 
       group_by(student) %>%
       mutate(WANT2 = replace(if(3 %in% score) replace(score, 
         (match(3, score) +1):n(), 3) else score, is.na(score) & drop == 1, 4))
    # A tibble: 14 x 5
    # Groups:   student [4]
    #   student score  drop  WANT WANT2
    #     <dbl> <dbl> <dbl> <dbl> <dbl>
    # 1       1     1     0     1     1
    # 2       1     2     0     2     2
    # 3       1     1     0     1     1
    # 4       1     1     0     1     1
    # 5       2     2     0     2     2
    # 6       2     3     0     3     3
    # 7       2     2     0     3     3
    # 8       2    NA     1     4     4
    # 9       3     3     0     3     3
    #10       3    NA     1     4     4
    #11       4     1     0     1     1
    #12       4     3     0     3     3
    #13       4     2     0     3     3
    #14       4     1     0     3     3
    

    【讨论】:

      【解决方案2】:

      使用data.table的选项:

      library(data.table)
      
      #if score = 1, WANT = 1 if score = 2, WANT = 2 if score = 3, WANT = 3
      setDT(data)[, w := score]
      
      #if score at t = 3 and score at any later scores are less than 3, they are replaced with 3.
      data[data[, .I[cummax(score)==3L & score < 3L], student]$V1, w := 3L]
      
      #it add student '5' which has NA values that I hope to fill with prior non-missing NA value
      data[, w := nafill(w, "locf")]
      
      #if drop = 1, WANT=4
      data[drop==1L, w := 4L]
      

      【讨论】:

      • 这太完美了,非常感谢。还有一个缺失的部分,如data2所示。我想要的是:如果分数是“NA”,那么我想用 data2 中所示的前一个值填充它。
      • 您的data2 与您的data 有什么关系?
      • 它添加了学生 '5',它有 NA 值,我希望用之前的非缺失 NA 值填充
      猜你喜欢
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多