简体   繁体   中英

R: Read in CSV decimal point and comma

Im a beginner, i want to read in a csv file with both . and , being a decimal separator. how can i do this in R. thanks

AllDataxx=read.csv("C:Sample.csv",
                  header=TRUE,sep=";",dec=", & .")

You cannot do this out of the box I am afraid. Of course what you can do is decide which you want say . , and use the colClasses argument to load the , columns as a character . Then you will use gsub(pattern= , ,replacement='.', x=yourColumnVector) to change the , into . and as.numeric to cast the vector to numeric

DF = data.frame(a=c(1.1,1.3,1.4),b=c('1,1','1,3','1,6'))
DF
    a   b
1 1.1 1,1
2 1.3 1,3
3 1.4 1,6
str(DF)
'data.frame':   3 obs. of  2 variables:
 $ a: num  1.1 1.3 1.4
 $ b: chr  "1,1" "1,3" "1,6"
DF$b = as.numeric(gsub(',','.',DF$b))
DF
    a   b
1 1.1 1.1
2 1.3 1.3
3 1.4 1.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM