R 2.13.1 (Mac OS X)
基本的に、私はから変換しようとしています:
"A|324,80|1.324,80|35,80-"
に
V1 V2 V3 V4
1 A 324.80 1324.8 -35.80
これで、インタラクティブに次の両方が機能します。
gsub("\\.","","1.324,80")
[1] "1324,80"
gsub("(.+)-$","-\\1", "35,80-")
[1] "-35,80"
また、それらを組み合わせます:
gsub("\\.", "", gsub("(.+)-$","-\\1","1.324,80-"))
[1] "-1324,80"
ただし、read.data から千単位の区切り文字を削除することはできません。
setClass("num.with.commas")
setAs("character", "num.with.commas", function(from) as.numeric(gsub("\\.", "", sub("(.+)-$","-\\1",from))) )
mydata <- "A|324,80|1.324,80|35,80-"
mytable <- read.table(textConnection(mydata), header=FALSE, quote="", comment.char="", sep="|", dec=",", skip=0, fill=FALSE,strip.white=TRUE, colClasses=c("character","num.with.commas", "num.with.commas", "num.with.commas"))
Warning messages:
1: In asMethod(object) : NAs introduced by coercion
2: In asMethod(object) : NAs introduced by coercion
3: In asMethod(object) : NAs introduced by coercion
mytable
V1 V2 V3 V4
1 A NA NA NA
「\\」から変更した場合は注意してください。関数内の "," に変更すると、状況が少し異なります。
setAs("character", "num.with.commas", function(from) as.numeric(gsub(",", "", sub("(.+)-$","-\\1",from))) )
mytable <- read.table(textConnection(mydata), header=FALSE, quote="", comment.char="", sep="|", dec=",", skip=0, fill=FALSE,strip.white=TRUE, colClasses=c("character","num.with.commas", "num.with.commas", "num.with.commas"))
mytable
V1 V2 V3 V4
1 A 32480 1.3248 -3580
問題は、read.data with dec="," が受信した "," を "." に変換することだと思います。as(from, "num.with.commas") を呼び出す前に、入力文字列がたとえば "1.324.80" になるようにします。
as("1.123,80-","num.with.commas") が -1123.80 を返し、as("1.100.123,80", "num.with.commas") が 1100123.80 を返すようにします。
入力文字列の最後の小数点以外のすべてを num.with.commas に置き換えるにはどうすればよいですか?
更新:最初に、否定先読みを追加し、コンソールで as() が機能するようにしました:
setAs("character", "num.with.commas", function(from) as.numeric(gsub("(?!\\.\\d\\d$)\\.", "", gsub("(.+)-$","-\\1",from), perl=TRUE)) )
as("1.210.123.80-","num.with.commas")
[1] -1210124
as("10.123.80-","num.with.commas")
[1] -10123.8
as("10.123.80","num.with.commas")
[1] 10123.8
ただし、read.table にはまだ同じ問題がありました。関数にいくつかの print() を追加すると、実際には num.with.commas がポイントではなくコンマを取得することがわかりました。
したがって、私の現在の解決策は、「、」から「。」に置き換えることです。num.with.commas で。
setAs("character", "num.with.commas", function(from) as.numeric(gsub(",","\\.",gsub("(?!\\.\\d\\d$)\\.", "", gsub("(.+)-$","-\\1",from), perl=TRUE))) )
mytable <- read.table(textConnection(mydata), header=FALSE, quote="", comment.char="", sep="|", dec=",", skip=0, fill=FALSE,strip.white=TRUE, colClasses=c("character","num.with.commas", "num.with.commas", "num.with.commas"))
mytable
V1 V2 V3 V4
1 A 324.8 1101325 -35.8