【问题标题】:How can copy a value in one column to rows with the same value in a different column in R? [duplicate]如何将一列中的值复制到R中不同列中具有相同值的行? [复制]
【发布时间】:2021-03-01 23:15:33
【问题描述】:

如果我有这样的事情:

id date        type     location
1  1/2/2021    student   Georgia
1                        Maine
1                        New York
2  2/20/2021   teacher   Florida 
2                        Louisiana 
3  2/15/2021   student   New York
3                        Maine
3                        California
3                        Florida

我想根据“id”的值复制“日期”和“类型”列中的值:

id date        type     location
1  1/2/2021    student   Georgia
1  1/2/2001    student   Maine
1  1/2/2001    student   New York
2  2/20/2021   teacher   Florida 
2  2/20/2021   teacher   Louisiana 
3  2/15/2021   student   New York
3  2/15/2021   student   Maine
3  2/15/2021   student   California
3  2/15/2021   student   Florida

我知道这可能已经问过了,但我不知道如何问这个问题。感谢您的帮助!

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以将空白"" 转换为NA 并使用fill

    library(dplyr)
    library(tidyr)
    df1 %>%
        mutate(across(c(date, type), na_if, "")) %>%
        group_by(id) %>%
        fill(date, type)
    

    或者另一种选择是通过'id'将其更改为first元素

    df %>%
       group_by(id) %>%
       mutate(across(c(date, type), first))
    

    【讨论】:

      【解决方案2】:

      这是一个data.table 选项

      > setDT(df)[, lapply(.SD, function(x) replace(x, is.na(x), na.omit(x))), id]
         id      date    type   location
      1:  1  1/2/2021 student    Georgia
      2:  1  1/2/2021 student      Maine
      3:  1  1/2/2021 student   New York
      4:  2 2/20/2021 teacher    Florida
      5:  2 2/20/2021 teacher  Louisiana
      6:  3 2/15/2021 student   New York
      7:  3 2/15/2021 student      Maine
      8:  3 2/15/2021 student California
      9:  3 2/15/2021 student    Florida
      

      数据

      > dput(df)
      structure(list(id = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L), date = c("1/2/2021",
      NA, NA, "2/20/2021", NA, "2/15/2021", NA, NA, NA), type = c("student",
      NA, NA, "teacher", NA, "student", NA, NA, NA), location = c("Georgia",
      "Maine", "New York", "Florida", "Louisiana", "New York", "Maine",
      "California", "Florida")), class = "data.frame", row.names = c(NA,
      -9L))
      

      【讨论】:

        猜你喜欢
        • 2016-09-28
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2021-07-20
        • 2021-06-02
        相关资源
        最近更新 更多