2017-02-09 27 views
-1

我拥有广泛的数据集,看起来像这样的工作:整理“并排侧”数据集

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?如果是这样,那么最优雅的方式是什么?

+0

'库(data.table); (setDT(wide_data),measure = patterns(“^ month”,“^ score”))' –

+0

谢谢!如果我的ID变量不仅仅是标准索引(例如date_S97和date_S94,而不是date_1和date_2),有什么方法可以在熔化的数据框中恢复这些变量? – joebruin

+0

请参阅[this](http://stackoverflow.com/questions/41883573/convert-numeric-representation-of-variable-column-to-original-string-following/) –

回答

0

通过搜索相关字符串的列名,可以将多个列绑定在一起。我在这里使用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