我正在尝试从R中的matrix
填充dataframe
# A demo Data Frame
d = data.frame(movie=c(1,2,3),user=c(1,3,2),rating=c(1,4,2))
# Initialize Output Matrix
output<-matrix(data=NA,nrow = length(d$movie),ncol = length(d$user),byrow = FALSE,)
#Function
# x= movie, y = user, input=data frame to be indexed, out = output matrix
getMatrixFilled<-function(x,y,input,out){
out[x,y]<-input[x,y];
out
}
我想采用movie
,user
和相应的rating
并将其置于矩阵
as
output[movie,user]<-rating
提前感谢您的帮助!!
输入
> d
movie user rating
1 1 1 1
2 2 3 4
3 3 2 2
所需输出
> outputM
[,1] [,2] [,3]
[1,] 1 NA NA
[2,] NA NA 4
[3,] NA 2 NA
答案 0 :(得分:2)
你可以尝试
output[as.matrix(d[1:2])] <- d$rating
output
# [,1] [,2] [,3]
#[1,] 1 NA NA
#[2,] NA NA 4
#[3,] NA 2 NA
答案 1 :(得分:1)
我怀疑你想要一个简单的重塑:
library(reshape2)
acast(d, movie ~ user)
# 1 2 3
#1 1 NA NA
#2 NA NA 4
#3 NA 2 NA
答案 2 :(得分:1)
由于我们正在猜测所需的输出,因此以下是其他几种与现有答案类似的替代方案:
xtabs(rating ~ movie + user, d)
# user
# movie 1 2 3
# 1 1 0 0
# 2 0 0 4
# 3 0 2 0
library(tidyr)
spread(d, user, rating)
# movie 1 2 3
# 1 1 1 NA NA
# 2 2 NA NA 4
# 3 3 NA 2 NA
并且(根据大众需求),基础R reshape
(但列的排序方式不同)......
reshape(d, direction = "wide", idvar = "movie", timevar = "user")
# movie rating.1 rating.3 rating.2
# 1 1 1 NA NA
# 2 2 NA 4 NA
# 3 3 NA NA 2
答案 3 :(得分:1)
我认为@akrun向您展示了最简单的方法。 (你几乎就在那里。但索引需要以矩阵的形式传递给"["
。)我发布了使用双列矩阵的应用程序,用于将分配索引到矩阵位置的格式为你要求的功能。
d = data.frame(movie=c(1,2,3),user=c(1,3,2),rating=c(1,4,2))
output<-matrix(data=NA,nrow = length(d$movie),ncol = length(d$user) )
getMatrixFilled<-function(x,y,input,out){
out[cbind(x,y)] <- input[ , "rating"]
out
}
getMatrixFilled(x=d$movie, y=d$user , input=d, out=output)
#--------------
[,1] [,2] [,3]
[1,] 1 NA NA
[2,] NA NA 4
[3,] NA 2 NA