簡體   English   中英

如何使用 R 重塑多行以分隔列 - 從長到寬?

[英]How to use R to reshape multiple rows to separate columns - long to wide?

我有以下df,

ID  event   eventdate1     date2       date3        date4     date5  index1   index2   index3
1   before               1/22/2020  
1   now                              10/20/2017   10/25/2017
1   later   03/02/2020                                                  0         1        0
1   tomo    05/05/2020                                                  0         0        0

我想把它改成寬的,預期的 output 是,

ID    date2     eventdate1      date3      date4       date5   index1   index2   index3
1   1/22/2020   05/05/2020   10/20/2017   10/25/2017             0         0        0

eventdate1 與事件相關。

eventdate1 將始終打印最后一個日期,即 tomo。

index1、index2 和 index3 也是如此。 所有其他日期在列中只有一個日期。

date5 為空,我希望保持為空

我希望使用重塑,但任何其他方法也可以。

使用dplyr您可以嘗試:

library(dplyr)

df %>%
  group_by(ID) %>%
  summarise(across(eventdate1:index3, ~{
                  x <- .[.!='']
                  if(length(x)) last(x) else ''
                  })) -> result

result

#     ID eventdate1 date2     date3      date4      date5 index1 index2 index3
#  <int> <chr>      <chr>     <chr>      <chr>      <chr> <chr>  <chr>  <chr> 
#1     1 05/05/2020 1/22/2020 10/20/2017 10/25/2017 ""    0      0      0   

對於舊版本的dplyr使用:

df %>%
  group_by(ID) %>%
  summarise_at(vars(eventdate1:index3), ~{
    x <- .[.!='']
    if(length(x)) last(x) else ''
  }) -> result

數據

df <- structure(list(ID = c(1L, 1L, 1L, 1L), event = c("before", "now", 
"later", "tomo"), eventdate1 = c("", "", "03/02/2020", "05/05/2020"
), date2 = c("1/22/2020", "", "", ""), date3 = c("", "10/20/2017", 
"", ""), date4 = c("", "10/25/2017", "", ""), date5 = c("", "", 
"", ""), index1 = c("", "", "0", "0"), index2 = c("", "", "1", "0"), 
index3 = c("", "", "0", "0")), row.names = c(NA, -4L), class = "data.frame")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM