0

每当我看到这个问题时,我的大脑就会关闭。我认为对其他人来说会很简单。
我有一个非常大的数据框,可以这样简化:

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

如果有人让我走到这一步,我可以轻松地创建一个新专栏好几天。我在数据处理方面做得越来越好,但有时我仍然会被这样的事情困住。

4

2 回答 2

2

使用基地:

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
于 2012-07-26T04:22:52.583 回答
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
于 2012-07-26T04:38:18.933 回答