我需要的:
我有一个非常大的数据框,其中包含以下列(还有一些其他列,但这些不重要)。以下是一个示例:
user_id video_id group_id x y
1 1 0 0 39 108
2 1 0 0 39 108
3 1 10 0 135 180
4 2 0 0 20 123
当然,用户、视频和组ID是重要因素。例如,有20个视频,但每个视频都有每个用户和组的多个“观察结果”。
我想将此数据框转换为以下格式,其中有与用户数量(N
)相同数量的x.N
,y.N
。
video_id x.1 y.1 x.2 y.2 …
0 39 108 20 123
因此,对于视频0
,用户1的x和y值分别在列x.1
和y.1
中。对于用户2,他们的值在列x.2
,y.2
等中。
我尝试过的方法:
我制作了一个数据框列表,该列表仅由每个video_id
的所有x,y
观察值组成:
summaryList = dlply(allData, .(user_id), function(x) unique(x[c("video_id","x","y")]) )
这就是它的外观:
List of 15
$ 1 :'data.frame': 20 obs. of 3 variables:
..$ video_id: Factor w/ 20 levels "0","1","2","3",..: 1 11 8 5 12 9 20 13 7 10 ...
..$ x : int [1:20] 39 135 86 122 28 167 203 433 549 490 ...
..$ y : int [1:20] 108 180 164 103 187 128 185 355 360 368 ...
$ 2 :'data.frame': 20 obs. of 3 variables:
..$ video_id: Factor w/ 20 levels "0","1","2","3",..: 2 14 15 4 20 6 19 3 13 18 ...
..$ x : int [1:20] 128 688 435 218 528 362 299 134 83 417 ...
..$ y : int [1:20] 165 117 135 179 96 328 332 563 623 476 ...
我遇到的问题:
还需要完成的任务包括:
Merge each data frame from thesummaryList
with each other, based on thevideo_id
. I can't find a nice way to access the actual data frames in the list, which aresummaryList[1]$`1`
,summaryList[2]$`2`
, et cetera.@James found out a partial solution:
Reduce(function(x,y) merge(x,y,by="video_id"),summaryList)
Ensure the column names are renamed after the user ID and not kept as-is. Right now my
summaryList
doesn't contain any info about the user ID, and the output ofReduce
has duplicate column names likex.x y.x x.y y.y x.x y.x
and so on.
Reduce(function(x,y) merge(x,y,by="video_id"),summaryList)
可能会起作用。 - Jamesvideo_id x.x y.x x.y y.y x.x y.x
等,而不是以用户ID命名的。 - slhcknames(reducedData)[-1] <- do.call(function(...) paste(...,sep="."),expand.grid(letters[24:25],names(summaryList)))
。 - James