我有一个包含userIds的列,但我想将此列更改为不同的行并合并same values in one row.
生成图像中数据的代码如下:
userid <- c(415,375,415,415,513,64,375,415,317,375)
rating <- c(4,4,4,5,5,4,3,5,4,5)
title <- c("GoldenEye (1995)","GoldenEye (1995)","Babe (1995)",
"Usual Suspects, The (1995)", "Braveheart (1995)","Braveheart (1995)","Braveheart (1995)",
"Braveheart (1995)","Apollo 13 (1995)","Apollo 13 (1995)")
data <- data.frame(userid,rating,title)
如何转换数据以使电影标题为列,每个用户标识一行,其中评级是数据框的单元格?
userid Apollo 13 (1995) Babe (1995) Braveheart (1995) GoldenEye (1995)
1 64 NA NA 4 NA
2 317 4 NA NA NA
3 375 5 NA 3 4
4 415 NA 4 5 4
5 513 NA NA 5 NA
Usual Suspects, The (1995)
1 NA
2 NA
3 NA
4 5
5 NA
>
答案 0 :(得分:3)
由于你没有给我们一个示例数据库,我创建了一个小数据库。我相信这可以解决你的问题:
library(tidyr)
library(data.table)
movies = data.table(userid = c(21, 24, 35, 21, 27, 35, 21),
movie = c("titanic","titanic", "titanic", "cinderella", "cinderella", "cinderella", "big hero"),
rating = c(1,3,4,2,1,5,3))
movies = spread(movies, key = movie, value = rating)
希望它有所帮助!