【问题标题】:Tidying "side-by-side" datasets [duplicate]整理“并排”数据集[重复]
【发布时间】:2017-02-09 07:00:06
【问题描述】:

我正在使用如下所示的广泛数据集:

library( tibble )
wide_data <- data_frame(month_1 = c("Jan", "Feb", "Mar", "Jun"),
                        score_1 = c(4, 5, 6, 4),
                        month_2 = c("Jan", "Mar", NA, NA),
                        score_2 = c(3, 2, NA, NA),
                        month_3 = c("Feb", "Mar", "Jun", NA),
                        score_3 = c(8, 7, 4, NA))

我想制作以下内容:

id month score
1  Jan   4
1  Feb   5
1  Mar   6
1  Jun   4
2  Jan   3
2  Mar   2
3  Feb   8  
3  Mar   7
3  Jun   4

请注意,初始数据集中的月份在观测值之间并不一致。 “整理”这个的最好方法是什么?我应该一次将基础数据读入 R 两列和 bind_rows 吗?如果是这样,最优雅的方法是什么?

【问题讨论】:

  • library(data.table) ; melt(setDT(wide_data), measure = patterns("^month", "^score"))
  • 谢谢!如果我的 ID 变量不仅仅是标准索引(例如 date_S97 和 date_S94 而不是 date_1 和 date_2),有没有办法恢复我融化的数据框中的那些?
  • 也许见this
  • 如何使用 dplyr 完成这项工作?

标签: r dplyr tidyr readr


【解决方案1】:

您可以通过在列名中搜索相关字符串来将多个列绑定在一起。我在这里使用grep 来实现这一点。

new <- data_frame(
    month = do.call( c, wide_data[ , grep( "^month_", names( wide_data ) ) ] ),
    score = do.call( c, wide_data[ , grep( "^score_", names( wide_data ) ) ] )
)

这给出了:

> new
# A tibble: 12 × 2
   month score
   <chr> <dbl>
1    Jan     4
2    Feb     5
3    Mar     6
4    Jun     4
5    Jan     3
6    Mar     2
7   <NA>    NA
8   <NA>    NA
9    Feb     8
10   Mar     7
11   Jun     4
12  <NA>    NA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2021-01-29
    • 2011-06-09
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多