Reputation: 165
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
Upvotes: 0
Views: 57
Reputation: 1790
If you want the fractions represented as numeric values you can use eval
together with parse
(as e.g. 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)
Upvotes: 1
Reputation: 211
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"
Upvotes: 0