【问题标题】:Reshaping a data.frame by its columns' combinations通过列的组合重塑 data.frame
【发布时间】:2021-10-26 17:33:27
【问题描述】:

我想知道如何将我的data 转换为我的预期输出?

data = expand.grid(time = 0:2, outcome = 1:2,group = c("control","treatment"))

#Expected output:

#time outcome group       
#0    1       "treatment1 - control"
#1    1       "treatment1 - control"
#2    1       "treatment1 - control"
#0    2       "treatment2 - control"
#1    2       "treatment2 - control"
#2    2       "treatment2 - control"

【问题讨论】:

    标签: r dataframe function dplyr tidyverse


    【解决方案1】:

    我们可以通过paste进行分组

    library(dplyr)
    library(stringr)
    data %>% 
       mutate(group = as.character(group),
         group = case_when(group =='treatment' ~ str_c(group, outcome),
               TRUE ~ group)) %>%
       group_by(outcome, time) %>%
       summarise(group = str_c(sort(group, decreasing = TRUE), 
          collapse = ' - '), .groups = 'drop') 
    

    -输出

    # A tibble: 6 x 3
      outcome  time group               
        <int> <int> <chr>               
    1       1     0 treatment1 - control
    2       1     1 treatment1 - control
    3       1     2 treatment1 - control
    4       2     0 treatment2 - control
    5       2     1 treatment2 - control
    6       2     2 treatment2 - control
    

    【讨论】:

    • @MartinGal 实际上,我没有在输出中看到“时间”列。我的错误
    • 嗨 Arun,我可以问一个关于 your answer 的问题吗?只是让我知道,以便我可以提出一个新问题? -- 谢谢。
    • @Reza 几个月前就已经回答了。你可以回答一个新问题
    • 当然,HERE 是新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    相关资源
    最近更新 更多