如何使用变量作为矩阵的坐标将数据帧转换为矩阵?

时间:2014-05-22 13:26:48

标签: r matrix dataframe

我有一个包含3列的数据框:

df<-data.frame(x=c(1,1,1,2,2,2,2,3,3), y=c(1,2,3,1,2,3,4,1,2), percentage=c(50,25,25,15,35,25,25,55,45))

看起来像:

  x y percentage
1 1 1         50
2 1 2         25
3 1 3         25
4 2 1         15
5 2 2         35
6 2 3         25
7 2 4         25
8 3 1         55
9 3 2         45

第三列表示x-ID对象(1 col)中y-ID对象(2 col)区域的百分比。

我想得到一个矩阵(或smthg相关),用x和y定义坐标/下标和&#34;百分比&#34;,矩阵的元素。

基本上,我想得到一个像这样的矩阵:

  1  2  3  4
1 50 25 25 0
2 15 35 25 25
3 55 45 0  0

有没有简单的方法来实现这一目标?

3 个答案:

答案 0 :(得分:4)

xtabs(percentage ~ x + y, data = df)

答案 1 :(得分:1)

如果xy中的元素是连续的自然数,请尝试:

df<-data.frame(x=c(1,1,1,2,2,2,2,3,3), y=c(1,2,3,1,2,3,4,1,2), percentage=c(50,25,25,15,35,25,25,55,45))
out <- matrix(0, nrow=length(unique(df$x)), ncol=length(unique(df$y)))
out[cbind(df$x, df$y)] <- df$percentage
out

##      [,1] [,2] [,3] [,4]
## [1,]   50   25   25    0
## [2,]   15   35   25   25
## [3,]   55   45    0    0

答案 2 :(得分:1)

使用data.table的解决方案:

# Load package
library(data.table)

# Set up data
dt <- data.table(x=c(1,1,1,2,2,2,2,3,3), y=c(1,2,3,1,2,3,4,1,2), percentage=c(50,25,25,15,35,25,25,55,45))

# Transform data  
m <- as.matrix(dcast.data.table(data=dt, x ~ y, value.var="percentage", fill=0)[,-1, with=FALSE])

# > m
#       1  2  3  4
# [1,] 50 25 25  0
# [2,] 15 35 25 25
# [3,] 55 45  0  0
相关问题