转置data.frame r

时间:2017-01-23 20:47:31

标签: r

我有我的数据框:

Name  Time  Event
Serg  15    Log1
Nate  15    Log2
Serg  10    Log3
Nate   9    Log1
Nate  20    Log5

我希望按照Name time的每个Name 1 2 3 Serg Log3 Log1 NA Nate Log1 Log2 Log5 按时间对其进行转置:

{{1}}
希望我解释清楚!感谢

1 个答案:

答案 0 :(得分:4)

我们可以使用dcast中的data.table。转换' data.frame'到' data.table' (setDT(df1)),然后dcast将数据集rowid扩展为'通过创建序列ID(data.table - 来自value.var的格式为' Name'变量),将其传递给公式,并将library(data.table) dcast(setDT(df1)[order(Name, Time)], Name ~ rowid(Name), value.var = "Event") # Name 1 2 3 #1: Nate Log1 Log2 Log5 #2: Serg Log3 Log1 NA 指定为& #34;事件"

tidyverse

或使用library(dplyr) library(tidyr) df1 %>% group_by(Name) %>% arrange(Name, Time) %>% mutate(ind = row_number()) %>% select(-Time) %>% spread(ind, Event) # Name `1` `2` `3` #* <chr> <chr> <chr> <chr> #1 Nate Log1 Log2 Log5 #2 Serg Log3 Log1 <NA>

           Date            Well   Elev
1    2002-05-23            MW-3 929.04
2    2002-05-29            MW-3 929.39
3    2002-05-31            MW-3 929.37
4    2002-06-05            MW-3 929.36
5    2002-06-12            MW-3     NA
6    2002-06-13            MW-3 929.47
7    2002-06-19            MW-3 929.42
8    2002-06-26            MW-3 930.02
9    2002-07-05            MW-3 930.00