重复数据框重复

Stu*_*art 8 r reshape2

我有什么应该是一个简单的重塑问题,但我无法弄清楚.部分数据如下所示:

foo <- structure(list(grade = c(3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 
3, 3, 4, 4, 5, 5, 6, 6), var.type = structure(c(3L, 2L, 3L, 2L, 
3L, 2L, 3L, 2L, 3L, 2L, 3L, 2L, 3L, 2L, 3L, 2L, 3L, 2L, 3L, 2L
), .Label = c("Raw Score", "SE", "SS"), class = "factor"), var.val = c(120L, 
47L, 120L, 46L, 120L, 46L, 120L, 47L, 120L, 46L, 120L, 46L, 120L, 
12L, 120L, 14L, 120L, 16L, 120L, 20L)), .Names = c("grade", "var.type", 
"var.val"), row.names = c(2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
11L, 12L, 13L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)

要么

  grade var.type var.val
2     3       SS     120
3     3       SE      47
4     4       SS     120
5     4       SE      46
6     5       SS     120
7     5       SE      46
Run Code Online (Sandbox Code Playgroud)

我想让它看起来像这样:

grade    SS    SE
3        120   47
4        120   46
5        120   46
Run Code Online (Sandbox Code Playgroud)

等等.我尝试过reshape,cast和dcast,就像在这个帖子中一样:

重塑数据集

但似乎没什么用.我真的很感激一些帮助.TIA.

seb*_*n-c 7

如果你想要重塑并且你有重复项,那么你需要为每一对赋予一个唯一的id:

foorle <- rle(foo$grade)
fooids <- rep(seq_len(length(foorle$values)), times=foorle$lengths)

fooids
 [1]  1  1  2  2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10
Run Code Online (Sandbox Code Playgroud)

现在,您将能够正确使用重塑:

idfoo <- cbind(id=fooids, foo)

library(reshape)
dcast(idfoo, id+grade~var.type, value.var="var.val")

   id grade SE  SS
1   1     3 47 120
2   2     4 46 120
3   3     5 46 120
4   4     6 47 120
5   5     7 46 120
6   6     8 46 120
7   7     3 12 120
8   8     4 14 120
9   9     5 16 120
10 10     6 20 120
Run Code Online (Sandbox Code Playgroud)

编辑:请注意我假设你的数据是有序的,否则你将有区别重复的问题.如果不是,您可以随时使用order它.