每当我看到这个问题,我的大脑都会关闭。我认为对其他人来说这很简单 我有一个非常大的数据框,可以这样简化:
day subject y variable
1 a 2.1
1 b 3.5
1 c 2.2
2 a 3.3
2 b 4.5
2 c 3.8
3 a 5.1
3 b 2.8
3 c 2.3
4 a 4.2
4 b 1.9
4 c 2.5
5 a 4.9
5 b 3.8
5 c 3.4
我想按主题列,例如:
a b c
2.1 3.5 2.2
3.3 4.5 3.8
5.1 2.8 2.3
4.2 1.9 2.5
4.9 3.8 3.4
如果某人让我达到这一点,我可以轻松地创建一个新列。我在数据操作方面做得越来越好,但有时候我仍然会遇到这样的问题。
答案 0 :(得分:2)
使用base:
dat <- structure(list(day = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L), subject = structure(c(1L, 2L, 3L, 1L, 2L,
3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("a", "b",
"c"), class = "factor"), y.variable = c(2.1, 3.5, 2.2, 3.3, 4.5,
3.8, 5.1, 2.8, 2.3, 4.2, 1.9, 2.5, 4.9, 3.8, 3.4)), .Names = c("day",
"subject", "y.variable"), class = "data.frame", row.names = c(NA,
-15L))
unstack(dat, y.variable~subject)
a b c
1 2.1 3.5 2.2
2 3.3 4.5 3.8
3 5.1 2.8 2.3
4 4.2 1.9 2.5
5 4.9 3.8 3.4
答案 1 :(得分:0)
你可以这么简单地做到这一点:
df <- data.frame(Subject = c("a","b","c","a","b","c","a","b","c","a","b","c","a","b","c"), y.variable = c(2.1, 3.5, 2.2, 3.3, 4.5,3.8, 5.1, 2.8, 2.3, 4.2, 1.9, 2.5, 4.9, 3.8, 3.4))
ind.a <- which(df$Subject == "a")
ind.b <- which(df$Subject == "b")
ind.c <- which(df$Subject == "c")
data.frame(a=df$y.variable[ind.a],b=df$y.variable[ind.b],c=df$y.variable[ind.c])
a b c
1 2.1 3.5 2.2
2 3.3 4.5 3.8
3 5.1 2.8 2.3
4 4.2 1.9 2.5
5 4.9 3.8 3.4