将矩阵转换为数值数据框

7

我有一些用矩阵保存的数据,但格式不太方便。所有列向量都是字符类型。

datamatrix <- structure(c("1", "2", "3", "4", "0.9301", "0.93", "0.9286", "0.9209", 
                          "0.9", "0.8064", "0.7947", "0.7607", "0.8042", "0.7847", "0.7832", 
                          "0.7578", "0.7487", "0.7105", "0.6566", "0.5951", "0.6951", "0.677", 
                          "0.6588", "0.5922", "0.6889", "0.6471", "0.6524", "0.5932"), .Dim = c(4L, 
                                                                                                7L))

我的目标是将这个矩阵转换为数据框,并将列向量转换为数值型。

我尝试了以下步骤:

1)

datamatrix2 <- as.data.frame(datamatrix)
datamatrix2 <- as.numeric(datamatrix2)

这会导致错误:

"Error: (list) object cannot be coerced to type 'double'"

2) 所以我尝试使用sapply:

datamatrix3 <- as.data.frame(sapply(datamatrix, as.numeric))

这将所有我之前拥有的列放在一个长列中。

3) 当我在已经转换为数据框(但仍然是字符向量)的数据上使用来自2)的apply函数时,它会从第一列(1,2,3,4)中取值并将其放入所有其他列中(但是以降序方式)。

datamatrix4 <- as.data.frame(sapply(datamatrix2, as.numeric))
2个回答

8

将矩阵转换为最好的方法是更改 mode。这样您可以使矩阵变为 numeric ,然后可以轻松地转换为数据框:

mode(datamatrix) = "numeric"
data.frame(datamatrix)
#   X1     X2     X3     X4     X5     X6     X7
# 1  1 0.9301 0.9000 0.8042 0.7487 0.6951 0.6889
# 2  2 0.9300 0.8064 0.7847 0.7105 0.6770 0.6471
# 3  3 0.9286 0.7947 0.7832 0.6566 0.6588 0.6524
# 4  4 0.9209 0.7607 0.7578 0.5951 0.5922 0.5932

2

有几种方法可以做到这一点。最简单的可能是使用 purrr::map_df()

library("purrr")
datamatrix = as.data.frame(datamatrix, stringsAsFactors = FALSE)
datamatrix = map_df(datamatrix, as.numeric)
datamatrix
# A tibble: 4 x 7
#      V1     V2     V3     V4     V5     V6     V7
#   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1 0.9301 0.9000 0.8042 0.7487 0.6951 0.6889
# 2     2 0.9300 0.8064 0.7847 0.7105 0.6770 0.6471
# 3     3 0.9286 0.7947 0.7832 0.6566 0.6588 0.6524
# 4     4 0.9209 0.7607 0.7578 0.5951 0.5922 0.5932

这句话明确要求返回数据框架。

在基本的R中,可以使用以下方式:

datamatrix = as.data.frame(datamatrix)
datamatrix = lapply(datamatrix, as.numeric)
datamatrix = as.data.frame(datamatrix)
str(datamatrix)

谢谢!我已经尝试了你提供的两个建议。不幸的是,两者都改变了数据中的值。第一列保持不变,但第2-7列得到了值(4,3,2,1)。在第一个建议中,值的更改发生在第二行代码(datamatrix = lapply(datamatrix, as.numeric))中,在第二个建议中,它也发生在第二行(datamatrix = map_df(datamatrix, as.numeric))。 - SCW16
1
@SCW16 是的,抱歉,忘记了 stringsAsFactors = FALSE。请看编辑后的答案。 - Phil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接