【问题标题】:How to read .txt data row-wise into table in R?如何将 .txt 数据逐行读取到 R 中的表中?
【发布时间】:2021-02-01 09:05:39
【问题描述】:

我有一个文本文件,我希望将其转换为 R 中的表格格式。

我曾尝试使用 read_table,但它会自动假定为 1 列。我应该如何读取数据,因为它们是按行列出的?

这是我的文本文件的样子:

Id:   0
Category: Toys

Id:   1
Category: Books
Price: 19.99
Rating: 4.03

Id:  2
Category: Toys Young-Children
Rating: 3

...


【问题讨论】:

  • 为什么不把文本栏读进去后直接转置呢?

标签: r row data-manipulation data-preprocessing


【解决方案1】:

您可以读取以冒号(:)为分隔符的数据,并将其重塑为宽格式。

我使用您共享的数据创建了一个名为temp.txt 的新文件,并使用read.table 读取它。

library(dplyr)
library(tidyr)

data <- read.table('temp.txt', sep = ':', strip.white = TRUE)

data %>%
  mutate(row = cumsum(V1 == 'Id')) %>%
  pivot_wider(names_from = V1, values_from = V2) %>%
  select(-row) %>%
  type.convert(as.is = TRUE)

#     Id Category            Price Rating
#  <int> <chr>               <dbl>  <dbl>
#1     0 Toys                 NA    NA   
#2     1 Books                20.0   4.03
#3     2 Toys Young-Children  NA     3   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多