【问题标题】:pivot multiple sets of columns at once一次旋转多组列
【发布时间】:2022-01-21 19:58:01
【问题描述】:

我有一个数据框,我在其中对一堆数据集进行了回归,然后获取这些数据集的子集并再次回归。这导致数据框的列显示“完整”数据集的斜率和截距以及标准误差,然后更多列显示“子集”数据集的这些内容。

我想将数据集转换为长格式,其中一列显示它是哪种类型(完整或子集),然后其他列显示斜率、se、截距等。

我已经找到了一种方法,方法是多次执行pivot_longer,然后过滤到枢轴创建的新列匹配的位置,但这不是最好的方法。我想知道是否有一种方法可以列出枢轴函数中的列集以跳过这一大块代码。代表下面。

# made dataframe
df <- 
  tribble(
    ~trial,   ~full_slope,    ~full_slope_se,    ~subset_slope,  ~subset_slope_se,
     1,            10,              1,                12,               2.5,
     2,             9,               1.2,             8.5,               3,
     3,             9.5,              2,               9.9,              3
  )


# pivot 

df %>%
  # first pivot the slope columns
  pivot_longer(cols = c(full_slope, subset_slope),
               names_to = "type",
               values_to = "slope") %>%

  # next pivot the SE columns
  pivot_longer(cols = c(full_slope_se, subset_slope_se),
               names_to = "type_se",
               values_to = "se") %>%

 # add a column for when they match up (slope and se both from same dataset, full or subset)
  mutate(
    data_type = 
      case_when(
        type == "full_slope" & type_se == "full_slope_se" ~ "full",
        type == "subset_slope" & type_se == "subset_slope_se" ~ "subset"
        )) %>%

  # remove rows that are musmatched
  filter(!is.na(data_type)) %>%

  # remove extra columns made by pivots
  select(-type, -type_se) %>%
  relocate(data_type, .after = trial)

这确实给了我想要的输出,我只是觉得这不是我应该这样做的方式。提前致谢!

【问题讨论】:

    标签: r pivot reshape tidyr data-manipulation


    【解决方案1】:

    使用names_pattern=:

    df %>%
      pivot_longer(-trial, names_pattern = "([^_]*)_(.*)", names_to = c("data_table", ".value"))
    # # A tibble: 6 x 4
    #   trial data_table slope slope_se
    #   <dbl> <chr>      <dbl>    <dbl>
    # 1     1 full        10        1  
    # 2     1 subset      12        2.5
    # 3     2 full         9        1.2
    # 4     2 subset       8.5      3  
    # 5     3 full         9.5      2  
    # 6     3 subset       9.9      3  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2014-12-16
      • 2015-02-14
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多