我有一个文本文件,我希望将其转换为 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 中的表格格式。
我曾尝试使用 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
...
您可以使用冒号 ( ) 作为分隔符读取数据:
并将其重塑为宽格式。
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