读取分隔文件,其中分号作为分隔符出现在字符串中

标签 r data.table

我正在尝试读取一个文件,其中某些行在文本字符串中包含额外的分号(我不知道是什么原因导致的)

作为示例,这是具有相同问题的 super 简化数据:

bad_data <- "100; Mc Donalds; Seattle; normal day
             115; Starbucks; Boston; normal day
             400; PF Chang; Chicago; busy day
             400;; Texas; busy day
             10; D;unkin Donuts; Washin;gton; lazy day"

所以它没有标题,我尝试用以下内容读取它:

library(data.table)
fread(bad_data, sep = ";", header = F, na.strings = c("", NA), strip.white = T)

但是没有雪茄...这有点难以阅读,如果没有干净的解决方案,我想跳过这些行。

最佳答案

如果您只想删除没有预期分隔符数量的行:

library(stringi)
library(magrittr)

bad_data <- 
"100; Mc Donalds; Seattle; normal day
115; Starbucks; Boston; normal day
400; PF Chang; Chicago; busy day
400;; Texas; busy day
10; D;unkin Donuts; Washin;gton; lazy day"

# split to lines. you could also use readLines if it's coming from a file
text_lines <- unlist(strsplit(bad_data, '\n'))

# which lines contain the expected number of semicolons?
good_lines <- sapply(text_lines, function(x) stri_count_fixed(x, ';') == 3)

# for those lines, split to vectors and (optional bonus) trim whitespace
good_vectors <- lapply(
  text_lines[good_lines], 
  function(x) x %>% strsplit(';') %>% unlist %>% trimws)

# flatten to matrix (from which you can make a data.frame or whatever you want)
my_mat <- do.call(rbind, good_vectors)

结果:

> my_mat
     [,1]  [,2]         [,3]      [,4]        
[1,] "100" "Mc Donalds" "Seattle" "normal day"
[2,] "115" "Starbucks"  "Boston"  "normal day"
[3,] "400" "PF Chang"   "Chicago" "busy day"  
[4,] "400" ""           "Texas"   "busy day"  

关于读取分隔文件,其中分号作为分隔符出现在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47931859/

相关文章:

r - 如何使用 R 中的 purrr 映射函数将 xml-nodesets(使用 rvest 创建)放入小标题中?

html - R 中的 cox 回归输出表或图

基于R中的第二个变量删除具有非唯一值的行?

arrays - 在 R 中的数组中复制列表的元素

r - 如果缺少,请使用另一数据框的值更新现有的 data.frame

r - 为什么R的data.table比pandas快得多?

r - 在 data.tables 列表中应用列函数

algorithm - 生成不超过一定数量的素数列表

r - R-创建大量data.table对象时性能降低

r - 在data.table中的多列上计算不同