2014-05-22 71 views
0

我有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 

第三列表示是內使y-ID的對象的區域(2列)的百分比x-ID對象(1列)。

我想獲得一個矩陣(或smthg相關)與x和y,定義座標/下標和「百分比」,矩陣的元素。

基本上,我想獲得一個這樣的矩陣:

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

是否有一個簡單的方法來實現這一目標?

回答

3
xtabs(percentage~x+y, data=df) 
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 
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