R如何将数据重塑为列变量以成为行名并提取特定的其他变量数据?

R how to reshape data as a column variable to become rownames and extract specific other variable data?

我在将融化的数据从长数据转换为宽数据并同时进行过滤时遇到了一些麻烦。 我之前可以继续进行子集化,但我想同时进行并将它们保存为不同的 tables.

ID,freq,Subject,Time
aaaaa,5545,M1,0
aaaaa,5471,M2,0
aaaaa,5029,M3,0
aaaaa,4531,M1,3h
aaaaa,4523,M2,3h
aaaaa,3915,M3,3h
aaaaa,3800,M1,1day
aaaaa,3609,M2,1day
aaaaa,3427,M3,1day
bbbb,3426,M1,0
bbbb,3272,M2,0
bbbb,3266,M3,0
bbbb,5545,M1,3h
bbbb,5471,M2,3h
bbbb,5029,M3,3h
bbbb,4532,M2,1day
bbbb,4533,M3,1day

这是我数据中的一个片段网。我想获得如下所示的 table 并将每个主题保存在不同的对象(M1、M2 和 M3...)中。我阅读并尝试重塑和施放命令,但无法管理我需要的东西。您如何管理如下所示的 table?感谢您的帮助和建议。

ID     0     3h   1day
aaaaa  5545 4531 3800
bbbb   3426 5545 4531

使用dcast你可以做到:

df <- reshape2::dcast(df, ID + Subject ~ Time, value.var = "freq")
df_list <- split(x, x$Subject)

$M1
                ID Subject    0 1day   3h
1            aaaaa      M1 5545 3800 4531
4             bbbb      M1 3426   NA 5545

$M2
                ID Subject    0 1day   3h
2            aaaaa      M2 5471 3609 4523
5             bbbb      M2 3272 4532 5471

另一种选择是:

library(dplyr)
library(tidyr)

df %>% 
spread(Time, freq) %>% 
group_split(., Subject)

数据

df <- structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("           aaaaa", 
"           bbbb"), class = "factor"), freq = c(5545L, 5471L, 
5029L, 4531L, 4523L, 3915L, 3800L, 3609L, 3427L, 3426L, 3272L, 
3266L, 5545L, 5471L, 5029L, 4532L, 4533L), Subject = structure(c(1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 3L
), .Label = c("M1", "M2", "M3"), class = "factor"), Time = structure(c(1L, 
1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L
), .Label = c("0", "1day", "3h"), class = "factor")), class = "data.frame", row.names = c(NA, 
-17L))