Replacing commas and dots in R

前端 未结 3 1370
名媛妹妹
名媛妹妹 2020-12-28 17:25

I have a whole column of numbers that include dot separators at the thousands and comma instead of dot as an dismal separator. When I try to create a numeric column out of t

3条回答
  •  清歌不尽
    2020-12-28 17:40

    For things like these I like scan() the most, because it is easy to understand. Just use

    scan(text=var1, dec=",", sep=".")
    

    Alas, it's not faster than gsub(), which on the other hand seemes overpowered. Hence another, and fast, option is sub():

    as.numeric(sub(",", ".", sub(".", "", var1, fixed=TRUE), fixed=TRUE))
    

    And just in case: When you're reading var1 from a file directly, just read it in with a specified separator: read.table("file.txt", dec=",", sep=".")

提交回复
热议问题