A5C*_*2T1 7 r fread data.table splitstackshape
可以fread从"data.table"强制成功使用"."作为sep值吗?
我正试图在"splitstackshape"中fread加速我的concat.split功能.请参见本要点对我采取的一般方法,以及这个问题我为什么要作出这样的转变.
我遇到的问题是将dot(".")视为一个值sep.每当我这样做时,我都会收到"意外字符"错误.
以下简化示例演示了此问题.
library(data.table)
y <- paste("192.168.1.", 1:10, sep = "")
x1 <- tempfile()
writeLines(y, x1)
fread(x1, sep = ".", header = FALSE)
# Error in fread(x1, sep = ".", header = FALSE) : Unexpected character (
# 192) ending field 2 of line 1
Run Code Online (Sandbox Code Playgroud)
我在当前函数中使用的解决方法是替换"."原始数据中希望不存在的另一个字符"|",但是这对我来说似乎有风险,因为我无法预测其他人的数据集中的内容.这是行动中的解决方法.
x2 <- tempfile()
z <- gsub(".", "|", y, fixed=TRUE)
writeLines(z, x2)
fread(x2, sep = "|", header = FALSE)
# V1 V2 V3 V4
# 1: 192 168 1 1
# 2: 192 168 1 2
# 3: 192 168 1 3
# 4: 192 168 1 4
# 5: 192 168 1 5
# 6: 192 168 1 6
# 7: 192 168 1 7
# 8: 192 168 1 8
# 9: 192 168 1 9
# 10: 192 168 1 10
Run Code Online (Sandbox Code Playgroud)
出于此问题的目的,假设数据是平衡的(每行将具有相同数量的" sep"字符).我知道使用a "."作为分隔符并不是最好的主意,但我只是想根据我在SO上回答的其他 问题 来考虑其他用户在他们的数据集中可能有的内容.
现已在 GitHub 上的 v1.9.5 中实现。
> input = paste( paste("192.168.1.", 1:5, sep=""), collapse="\n")
> cat(input,"\n")
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
Run Code Online (Sandbox Code Playgroud)
设置sep='.'新参数会导致歧义dec(默认情况下'.'):
> fread(input,sep=".")
Error in fread(input, sep = ".") :
The two arguments to fread 'dec' and 'sep' are equal ('.')
Run Code Online (Sandbox Code Playgroud)
因此选择其他的东西dec:
> fread(input,sep=".",dec=",")
V1 V2 V3 V4
1: 192 168 1 1
2: 192 168 1 2
3: 192 168 1 3
4: 192 168 1 4
5: 192 168 1 5
Run Code Online (Sandbox Code Playgroud)
您可能会收到警告:
> fread(input,sep=".",dec=",")
V1 V2 V3 V4
1: 192 168 1 1
2: 192 168 1 2
3: 192 168 1 3
4: 192 168 1 4
5: 192 168 1 5
Warning message:
In fread(input, sep = ".", dec = ",") :
Run again with verbose=TRUE to inspect... Unable to change to a locale
which provides the desired dec. You will need to add a valid locale name
to getOption("datatable.fread.dec.locale"). See the paragraph in ?fread.
Run Code Online (Sandbox Code Playgroud)
忽略或抑制警告,或阅读该段落并设置选项:
options(datatable.fread.dec.locale = "fr_FR.utf8")
Run Code Online (Sandbox Code Playgroud)
这确保了不会有任何歧义。