将csv中的Currency值导入R [英] Import Currency values in csv into R
问题描述
我正在尝试导入包含带有£"和,"的几列值的csv文件.
I am trying to import a csv file with several columns of values with "£" and ",".
数据框例如:
channel1 channel2
£100,000 £400,000
£200,000 £500,000
£300,000 £600,000
read.csv()
给了我一个错误.在将值读取为字符之后,我尝试使用 sub
/ gsub
,但是它没有起作用.
read.csv()
has given me an error. I tried to use sub
/gsub
after reading the values as characters but it hasn't been working.
您能建议一种读取此文件的方法吗?
Can you please suggest an approach to read this file?
推荐答案
您确实应该从输入文件中发布几行未经编辑的材料.如果确实有逗号作为分隔符,并且列值中也有逗号,则几乎没有希望.这将带引号的值之间用逗号分隔:
You really ought to post a couple of lines of un-editted material from the input file. If you really do have commas as separators and also have commas within column values then it's pretty much hopeless. This will bring in quoted values that are separated by commas:
setClass("poundFmt")
setAs("character", "poundFmt",
function(from) as.numeric( gsub(",", "", gsub("£", "", from,fixed=TRUE),fixed=TRUE)))
dat <- read.table(text= "'channel1', 'chan2'
'£100,000', '£400,000'
'£200,000', '£500,000'
'£300,000', '£600,000'" , sep=",", header=TRUE, colClasses="poundFmt", stringsAsFactors=FALSE)
str(dat)
#---------------------
'data.frame': 3 obs. of 2 variables:
$ channel1: num 1e+05 2e+05 3e+05
$ chan2 : num 4e+05 5e+05 6e+05
这篇关于将csv中的Currency值导入R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!