[英]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. 我正在尝试找到一种将其导出为数据框的方式,以便它是数字形式的,并且不强制使用“ NA”。 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). 如果您希望分数表示为数值,则可以将eval
与parse
一起使用(例如,链接说明了@SymbolixAU给了您)。
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.