根据数据创建矩阵

时间:2018-11-01 18:07:17

标签: r stata

我有一个包含三列的数据,如下所示:

ppl loc1 loc2 
 1   US  CH   
 1   US  KR  
 1   US  CAN 
 1   CAN KR
 1   KR  CH
 1   CH  US
 1   CAN CH
 1   US  US

我想创建一个看起来像这样的矩阵:

       US CH KR CAN
    US 1  2  1  1  
    CH 2  0  1  1
    KR 1  1  0  0
   CAN 1  1  1  0

任何建议都会很棒。

3 个答案:

答案 0 :(得分:1)

R答案:

您只能matrix用于数字向量。对于您的情况,因为您有字符串,所以应该像这样使用data.frame

ppl <- rep(1,8)
loc1 <- c("US", "US", "US", "CAN", "KR", "CH", "CAN", "US")
loc2 <- c("CH","KR"  ,"CAN" ,"KR","CH","US","CH","US")

mat <- matrix(ppl, loc1, loc2) #error
df <- data.frame(ppl, loc1, loc2, stringsAsFactors = F)
> df
  ppl loc1 loc2
1   1   US   CH
2   1   US   KR
3   1   US  CAN
4   1  CAN   KR
5   1   KR   CH
6   1   CH   US
7   1  CAN   CH
8   1   US   US

答案 1 :(得分:1)

R答案:

这应该起作用:     y <-unique(data [,2])

x <- unique(data[,3])
mat <- matrix(NA,length(x),length(y))

for(i in 1:nrow(mat)){
  for(j in 1:rcol(mat)){
    mat[i,j] <- sum(as.numeric(data[,2] == y[j] & data[,3] == x[i]))
  }
}

答案 2 :(得分:1)

Stata答案:

clear 
input ppl str3 (loc1 loc2) 
 1   US  CH   
 1   US  KR  
 1   US  CAN 
 1   CAN KR
 1   KR  CH
 1   CH  US
 1   CAN CH
 1   US  US
 end 

 tab loc1 loc2, matcell(whatever) 

 mat li whatever 

whatever[4,4]
    c1  c2  c3  c4
r1   0   1   1   0
r2   0   0   0   1
r3   0   1   0   0
r4   1   1   1   1

有关添加行和列的名称,请参见help matrix