【问题标题】:Loading a matrix from a csv (dataframe) to R将矩阵从 csv(数据帧)加载到 R
【发布时间】:2021-09-13 22:25:03
【问题描述】:

我在 csv 中有这种格式的数据

state1       state2       state3
  1             0            0
  1             0            0
  0             0            1

我希望在 R 中的矩阵中像这样

1     0     0
1     0     0
0     0     1

我尝试将 csv 作为数据框加载并将其放入矩阵中,但它确实给出了预期的结果。使用这段代码,我得到了这个输出

df <- read_csv('filepath')
m <- matrix(df)

matrix format output:

1     1     0
0     0     0
0     0     1

这实质上使一列成为一行,而不是保留最初存储的内容。我希望矩阵保持与 csv 文件中相同的结构。

【问题讨论】:

  • 使用as.matrix(df)

标签: r dataframe matrix


【解决方案1】:

你必须转换t()的结果:

m <- t(as.matrix(read_csv('filepath')))
m
## 1     0     0
## 1     0     0
## 0     0     1

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多