将字符串与as.numeric的转换与如何使用read.fwf进行比较。
as.numeric("457") # 457
as.numeric("4 57") # NA with warning message现在从包含“5 7 12 4”的文件"fwf.txt“中读取。
foo<-read.fwf('fwf.txt',widths=c(5,5),colClasses='numeric',header=FALSE)
V1 V2
1 57 124
foo<-read.fwf('fwf.txt',widths=c(5,5),colClasses='character',header=FALSE)
V1 V2
1 5 7 12 4现在,我将注意到,在“数字”版本中,read.fwf的连接方式与Fortran相同。我只是有点惊讶,因为它没有以与NA相同的方式抛出错误或as.numeric。有人知道为什么吗?
发布于 2014-06-27 02:14:56
正如@eipi10 10所指出的,空间消除行为并不是read.fwf独有的行为。它实际上来自scan()函数( read.table使用它,read.fwf使用它)。实际上,scan()函数在处理输入流时,将从任何不是字符的值中移除空格(或制表符,如果没有指定为分隔符)。一旦它得到了空格的“清除”值,那么它就会使用与as.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您可以在scan()中找到/src/main/scan.c的源代码,负责此行为的特定部分是around this line。
如果您希望as.numeric表现得像这样,您可以创建一个新的函数,如
As.Numeric<-function(x) as.numeric(gsub(" ", "", x, fixed=T))为了得到
As.Numeric("4 57")
# [1] 457https://stackoverflow.com/questions/24438022
复制相似问题