r - 如何在 R 中读取具有不同列数的 CSV 文件

标签 r csv import read.table sparse-columns

我有一个 csv 格式的稀疏数据集,其列数长度各不相同。这是文件文本的示例。

12223, University
12227, bridge, Sky
12828, Sunset
13801, Ground
14853, Tranceamerica
14854, San Francisco
15595, shibuya, Shrine
16126, fog, San Francisco
16520, California, ocean, summer, golden gate, beach, San Francisco

当我使用时

read.csv("data.txt", header = F)

R 会将数据集解释为具有 3 列,因为大小是根据前 5 行确定的。有没有办法强制 r 将数据放入更多列中?

最佳答案

?read.table 文档深处有以下内容:

The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary (as in the ‘Examples’).

因此,我们将 col.names 定义为长度 X(其中 X 是数据集中的最大字段数),并设置 fill = TRUE:

dat <- textConnection("12223, University
12227, bridge, Sky
12828, Sunset
13801, Ground
14853, Tranceamerica
14854, San Francisco
15595, shibuya, Shrine
16126, fog, San Francisco
16520, California, ocean, summer, golden gate, beach, San Francisco")

read.table(dat, header = FALSE, sep = ",", 
  col.names = paste0("V",seq_len(7)), fill = TRUE)

     V1             V2             V3      V4           V5     V6             V7
1 12223     University                                                          
2 12227         bridge            Sky                                           
3 12828         Sunset                                                          
4 13801         Ground                                                          
5 14853  Tranceamerica                                                          
6 14854  San Francisco                                                          
7 15595        shibuya         Shrine                                           
8 16126            fog  San Francisco                                           
9 16520     California          ocean  summer  golden gate  beach  San Francisco

如果最大字段数未知,您可以使用漂亮的实用函数 count.fields (我在 read.table 示例代码中找到它):

count.fields(dat, sep = ',')
# [1] 2 3 2 2 2 2 3 3 7
max(count.fields(dat, sep = ','))
# [1] 7

可能有用的相关阅读:Only read limited number of columns in R

关于r - 如何在 R 中读取具有不同列数的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18922493/

相关文章:

统计csv中特定单词出现次数的Python算法

mysql - 将 CSV 导入 MySQL - 偏移 1 列

java - 从 JAR 文件导入安全类

r - R 中的比例树形图

r - 如何用 R 中的第 5 个和第 95 个百分位值替换异常值

r - 如何在 R 中使用 WMS?

sql-server-2008 - 导出和导入数据库中的选定行

r - data.table 和表意外行为

c# - 在 C# 中将字符串数组转换为一个枚举

php - 当我将查询结果导出到 Excel CSV 时,始终显示 HTML 代码