使用索引将数据帧转换为矩阵

时间:2019-06-25 12:15:13

标签: r dataframe matrix

我有一个如下数据框:

df<- read.table(text = "A   B   C
a1  abcd    1
b2  abcd    -1
c2  efgh    1
v4  uh  1
g5  vghvb   0
",header=T)

我想转换成这样的矩阵:

    abcd    abcd    efgh    uh  vghvb
a1  1   0   0   0   0
b2  -1  0   0   0   0
c2  0   0   1   1   0
v4  0   0   0   0   0
g5  0   0   0   0   1

我使用了这些代码,但是它们不起作用:

# get names for row and columns
nameVals <- sort(unique(unlist(df[1:2])))
# construct 0 matrix of correct dimensions with row and column names
myMat <- matrix(0, length(nameVals), length(nameVals), dimnames = list(nameVals, nameVals))

# fill in the matrix with matrix indexing on row and column names
myMat[as.matrix(df[c("A", "B")])] <- df[["C"]]

但是没有正确的结果,知道吗?

0 个答案:

没有答案