简体   繁体   中英

How to convert a symmetrical character matrix to a numerical data frame?

I have a symmetrical matrix similar to the following where the elements are characters. I'm trying to find a way to export it as a data frame so that it is numerical and no "NA" is coerced. I also want to keep row names and column names (not indices but the actual names).

  MYmatrix<- structure(c("0", "2/10", "2/10", "2/10", "0", "3/10", "2/10", 
"3/10", "0"), .Dim = c(3L, 3L), .Dimnames = list(c("t534", "t535", 
"t830"), c("t534", "t535", "t830")))

Thanks

If you want the fractions represented as numeric values you can use eval together with parse (as eg the link stated that @SymbolixAU gave you).

Here is a matrix with numeric entries:

MYmatrix02 <- matrix(sapply(MYmatrix, function(x) eval(parse(text = x))),
    nrow = nrow(MYmatrix), dimnames = dimnames(MYmatrix))

> MYmatrix02
     t534 t535 t830
t534  0.0  0.2  0.2
t535  0.2  0.0  0.3
t830  0.2  0.3  0.0

Or if you want a data frame:

MYdataframe <- as.data.frame(MYmatrix02)

Like this?

library(Matrix)
s<-matrix(as.factor(letters[1:25]),5)
s[lower.tri(s)] = t(s)[lower.tri(s)]
s[ row(s) == col(s) ] <- 0
s
      [,1] [,2] [,3] [,4] [,5]
 [1,] "0"  "f"  "k"  "p"  "u" 
 [2,] "f"  "0"  "l"  "q"  "v" 
 [3,] "k"  "l"  "0"  "r"  "w" 
 [4,] "p"  "q"  "r"  "0"  "x" 
 [5,] "u"  "v"  "w"  "x"  "0" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM