我正在尝试使用fread()
从网站获取一些数据。使用逗号分隔符可以方便地设置数据,但是我收到错误:
1: In fread("https://website.com/") :
Stopped early on line 56. Expected 5 fields but found 6. Consider fill=TRUE and comment.char=. First discarded non-empty line: <<0,1,1,x[[0], [1]],0>>
这是因为第56行之前的条目在第4列上有空白,所以类似于<<1,1,1,0>>
,而第56行包含第4列的逗号,因此它将其拆分为两列。现在,我希望整个x[[y], [z]]
在一个单元格中,所以我希望我的数据用逗号分隔,但不是当逗号在方括号内时。
编辑:真正的网站是私有的,所以在这里链接它是没有意义的,但它只包含csv格式的数据。就像是:
field1,field2,field3,field4,field5
1,0,0,,1
0,0,0,,1
1,1,0,,1
1,1,0,,1
............
0,1,1,x[[0], [1]],0
0,1,0,x[[0], [1]],1
1,0,1,,1
0,0,1,x[[1], [0]],0
............
问题出现在x[[0], [1]]
应该是一个单元格中,但由于逗号分隔符,它被分成两个单元格。
有什么方法可以用fread()?
或任何其他具有类似用途的功能吗?
提前谢谢你,如果这个问题有点基础,我很抱歉,我刚刚开始使用R.
您可以先使用fread
直接从您的私人网站上读取CSV文件,然后再下载:
csv_lines <- read_lines(my_weird_csv_text)
;"(?!\\])(\\,)(?!\\s\\[)"
拆分那些读取行,而不是使用单个逗号","
(这确保那些表达式中使用"[["
和"]]"
的逗号不用作拆分字符);split_lines
)定义已经从split_lines
强制的新数据帧/ tibble的列名。我希望它很清楚。
基本上,我们必须通过逐行阅读,然后根据处理特殊情况的正则表达式进行拆分,绕过简单的读取函数,如fread
或其他等效函数。
library(readr)
library(data.table)
library(stringr)
library(tibble)
my_weird_csv_text <-
"field1,field2,field3,field4,field5
1,0,0,,1
0,0,0,,1
1,1,0,,1
1,1,0,,1
0,1,1,x[[0], [1]],0
0,1,0,x[[0], [1]],1
1,0,1,,1
0,0,1,x[[1], [0]],0"
csv_lines <- read_lines(my_weird_csv_text)
split_lines <- stringr::str_split(csv_lines, "(?!\\])(\\,)(?!\\s\\[)", simplify = TRUE)
as_tibble(split_lines[-1, ]) %>%
`colnames<-`(split_lines[1, ]) -> tbl
tbl
#> # A tibble: 8 x 5
#> field1 field2 field3 field4 field5
#> <chr> <chr> <chr> <chr> <chr>
#> 1 1 0 0 "" 1
#> 2 0 0 0 "" 1
#> 3 1 1 0 "" 1
#> 4 1 1 0 "" 1
#> 5 0 1 1 x[[0], [1]] 0
#> 6 0 1 0 x[[0], [1]] 1
#> 7 1 0 1 "" 1
#> 8 0 0 1 x[[1], [0]] 0
一条建议:
从文档:
'fread' is for regular delimited files; i.e., where every row has the same number of
columns.
如果由于文件生成错误而导致列数变化或不规则,则像readLines
这样的替代方法将使您能够逐行处理文件 - 可能使用gsub
等正则表达式。