【问题标题】:Reformatting dataframe in R在 R 中重新格式化数据框
【发布时间】:2021-11-09 23:56:21
【问题描述】:

我有一个像这样的 DF:

  (Intercept)        W          Q
1  0.09282078 2.370789 -0.2478352
2  0.11608078 1.890222 -0.3134176
3  0.09899802 1.764213 -0.1406203

如何在dplyr 中重新格式化它,使其看起来像这样:

Feature      coeff
1_intercept  0.09282078
1_W          2.370789
1_Q          -0.2478352
2_intercept  0.11608078
2_W          1.890222
2_Q          -0.3134176
3_intercept  0.09899802
3_W          1.764213
3_Q          -0.1406203

【问题讨论】:

    标签: r dataframe dplyr reshape


    【解决方案1】:

    有了tidyverse,我们可以做到

    library(dplyr)
    library(tidyr)
    df1 %>%
        as.data.frame %>%
        mutate(rn = row_number()) %>%
        pivot_longer(cols = -rn, names_to = 'Feature', values_to = 'coeff') %>%
        unite(Feature, rn, Feature, sep= "_")
    

    【讨论】:

      【解决方案2】:

      以下是我的基本 R 尝试

      transform(
        setNames(rev(stack(df)),c("Feature","coeff")),
        Feature = paste0(ave(seq_along(Feature), Feature, FUN = seq_along), "_", Feature)
      )[order(rep(seq(ncol(df)),nrow(df))),]
      

      给了

              Feature       coeff
      1 1_(Intercept)  0.09282078
      4           1_W  2.37078900
      7           1_Q -0.24783520
      2 2_(Intercept)  0.11608078
      5           2_W  1.89022200
      8           2_Q -0.31341760
      3 3_(Intercept)  0.09899802
      6           3_W  1.76421300
      9           3_Q -0.14062030
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        相关资源
        最近更新 更多