0

I have a data frame like below:

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

and I want to convert to a matrix like this:

    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

I used these codes but they did not work:

# 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"]]

But no correct result, any idea?

makeyourownmaker
  • 1,558
  • 2
  • 13
  • 33
minoo
  • 555
  • 5
  • 20
  • Search for "reshape long-to-wide". – zx8754 Jun 25 '19 at 12:17
  • Why do you have 2 "abcd" columns? Please check solutions in linked post, let us know if it doesn't work for you. – zx8754 Jun 25 '19 at 12:24
  • If you want to continue with your matrix method, you can do `m1 <- matrix(0, dimnames = list(df$A, df$B), nrow = length(df$A), ncol = length(df$B))` and then do `m1[cbind(match(df$A, rownames(m1)), match(df$B, colnames(m1)))] <- df$C` – Ronak Shah Jun 25 '19 at 12:24
  • @zx8754 I did it but it did not work. It showed me something like this 1 NA NA NA 1 NA NA NA NA NA NA NA NA NA -1 NA NA NA NA NA NA NA NA NA NA NA NA. Would you please help – minoo Jun 25 '19 at 12:36
  • @zx8754 This is a subtract of my data frame and it is like this I have multiple names in the secnd columns. – minoo Jun 25 '19 at 12:37
  • 1
    This works: `tidyr::spread(df, key = B, value = C, fill = 0)`, we need to set fill option, so that we get zeros instead of NAs. – zx8754 Jun 25 '19 at 12:43

0 Answers0