R 从文本到数字的转换可能不一致
比较R 从文本到数字的转换可能不一致,r,type-conversion,R,Type Conversion,比较as.numeric与read.fwf转换字符串的方式 as.numeric("457") # 457 as.numeric("4 57") # NA with warning message 现在从一个文件“fwf.txt”中读取,该文件正好包含“571124” foo正如@eipi10所指出的,空格消除行为并非只有read.fwf。它实际上来自scan()函数(由read.table使用,由read.fwf使用)。实际上,scan()函数在处理输入流时,将从任何非字符值中删除空格(或
as.numeric
与read.fwf
转换字符串的方式
as.numeric("457") # 457
as.numeric("4 57") # NA with warning message
现在从一个文件“fwf.txt”中读取,该文件正好包含“571124”
foo正如@eipi10所指出的,空格消除行为并非只有read.fwf
。它实际上来自scan()
函数(由read.table
使用,由read.fwf
使用)。实际上,scan()函数在处理输入流时,将从任何非字符值中删除空格(或制表符,如果它们未指定为分隔符)。一旦它“清除”了空格的值,那么它将使用与.numeric相同的函数将该值转换为数字。对于字符值,它不会删除任何空格,除非您设置strip.white=TRUE
,这只会删除值开头和结尾的空格
观察这些例子
scan(text="TRU E", what=logical(), sep="x")
# [1] TRUE
scan(text="0 . 0 0 7", what=numeric(), sep="x")
# [1] 0.007
scan(text=" text ", what=character(), sep="~")
# [1] " text "
scan(text=" text book ", what=character(), sep="~", strip.white=T)
# [1] "text book"
scan(text="F\tALS\tE", what=logical(), sep=" ")
# [1] FALSE
您可以在/src/main/scan.c
中找到scan()
的源代码,负责此行为的特定部分是
如果希望as.numeric
的行为类似,可以创建一个新函数,如
As.Numeric<-function(x) as.numeric(gsub(" ", "", x, fixed=T))
read.fwf
调用read.table
,该函数处理colClasses
。使用read.table
而不是read.fwf
可以获得相同的行为。例如,如果将文件内容更改为“5 7 | 12 4”,然后使用read.table(“fwf.txt”,header=FALSE,sep=“|”,colClasses=“numeric”)
读取文件,则会得到相同的结果。我想,read.table
必须去掉数字字符之间的空格,因为它知道类应该是数字的,但是在查看函数代码时,我无法确定是否发生了这种情况。
As.Numeric<-function(x) as.numeric(gsub(" ", "", x, fixed=T))
As.Numeric("4 57")
# [1] 457