【问题标题】:Reshaping table: Widen table by repeating multiple columns per year重塑表格:通过每年重复多个列来扩大表格
【发布时间】:2021-04-14 16:02:42
【问题描述】:

为了正确运行绘图代码,我想重塑我的 data.table。

我的数据表目前看起来是这样的:

df <- data.frame(culture=c("A","B","C","D","A","B","C","D","A","B","C","D"),
             

Year=c("2000","2000","2000","2000","2001","2001","2001","2001","2002","2002","2002","2002"),
             a=rep(1:6,2),
             b=rep(6:11,2),
             c=rep(10:15,2))

我想获得的表应该每年重复列名 a、b 和 c。所需列:culture、a_2000、b_2000、c_2000、a_2001、b_2001、c_2001、a_2002、b_2002、c_2002

有没有简单的方法可以做到这一点?

我试过了:

df1<-df %>% pivot_wider(names_from = c(3:6), values_from = value)

df1<-df %>% spread(key=c(a,b,c), value, fill=NA)

df1<-df %>% nest(a,b,c, .key = 'value_col') %>% spread(key=Jahr, value=value_col) %>% unnest('2000', '2001', '2002', .sep = '_')

从我失败的尝试中可以看出,我还没有 r 经验。

最后一次尝试我得到的建议来自:https://community.rstudio.com/t/spread-with-multiple-value-columns/5378 然而这也不起作用

有什么建议吗?

【问题讨论】:

    标签: r loops reshape spread


    【解决方案1】:

    这是一种 pivot_wider 方法:

    library(tidyr)
    df %>%
      pivot_wider(id_cols = culture, names_from = Year,
                  values_from = !c(culture,Year))
    # A tibble: 4 x 10
      culture a_2000 a_2001 a_2002 b_2000 b_2001 b_2002 c_2000 c_2001 c_2002
      <chr>    <int>  <int>  <int>  <int>  <int>  <int>  <int>  <int>  <int>
    1 A            1      5      3      6     10      8     10     14     12
    2 B            2      6      4      7     11      9     11     15     13
    3 C            3      1      5      8      6     10     12     10     14
    4 D            4      2      6      9      7     11     13     11     15
    

    还有其他方法可以选择values_from 列。查看help(tidyr_tidy_select)

    此外,您可以使用names_glue = 控制列名的制作方式:

    df %>%
      pivot_wider(id_cols = culture, names_from = Year,
                  values_from = !c(culture,Year),
                  names_glue = "Year_{Year}_{.value}")
    # A tibble: 4 x 10
      culture Year_2000_a Year_2001_a Year_2002_a Year_2000_b Year_2001_b Year_2002_b Year_2000_c Year_2001_c Year_2002_c
      <chr>         <int>       <int>       <int>       <int>       <int>       <int>       <int>       <int>       <int>
    1 A                 1           5           3           6          10           8          10          14          12
    2 B                 2           6           4           7          11           9          11          15          13
    3 C                 3           1           5           8           6          10          12          10          14
    4 D                 4           2           6           9           7          11          13          11          15
    

    【讨论】:

    • 这是完美的。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多