【问题标题】:Is there a way to create and insert new rows in one column based on another column有没有办法根据另一列在一个列中创建和插入新行
【发布时间】:2019-11-06 12:49:35
【问题描述】:

我想在一列中收集一些事件数据。目前,数据包括事件列和包含某些事件结果的其他列。我想将结果作为事件包含在数据中并保留顺序。在下面的示例中,数据看起来像df,我想对它们进行转换,使它们看起来像desired df。

a <- c("event1","event2","event3","event4")
b <- c("outcome1",'','','')
c <- c('','',"outcome3",'')

df <- data.frame(a,b,c)

d <- c("event1","outcome1","event2","event3","outcome3","event4")
desired <- data.frame(d)

【问题讨论】:

    标签: r dplyr tidyverse data-manipulation


    【解决方案1】:

    我们可以通过转置将数据转换为矩阵,将其折叠成一个向量并删除空值

    vals <- c(t(df))
    data.frame(d = vals[vals!= ""])
    
    #         d
    #1   event1
    #2 outcome1
    #3   event2
    #4   event3
    #5 outcome3
    #6   event4
    

    使用tidyverse

    library(dplyr)
    tidyr::pivot_longer(df, cols = names(df)) %>%
       filter(value != "") %>%
       select(value)
    

    【讨论】:

    • 太好了,非常感谢您提供的有用答案!我会尽快接受
    猜你喜欢
    • 1970-01-01
    • 2020-01-02
    • 2021-12-11
    • 2022-08-12
    • 2023-02-22
    • 2023-03-25
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多