Convert from string to double - “NAs introduced by coercion”

前端 未结 1 1676
無奈伤痛
無奈伤痛 2021-01-16 01:30

I have a String List which looks like that:

> (eventWindow_120After_CDaxReturnList)
  [1] \"0,625955157\"  \"0,891329602\"  \"-0,933230106\"          


        
相关标签:
1条回答
  • 2021-01-16 01:55

    You have a problem with your decimal separators (R assumes . by default). The simplest solution is probably just to convert commas to periods (full stops)

    testDat <- c("0,123","2,13","na")
    as.double(gsub(",",".",testDat))
    

    You will still get some warnings due to the "na" values in your data set; you could avoid the warnings by converting the "na" values separately, as follows:

    NAvals <- testDat=="na"
    res <- numeric(length(testDat))
    res[NAvals] <- NA
    res[!NAvals] <- as.double(gsub(",",".",testDat[!NAvals]))
    

    There may also be some way to reset your locale (?Sys.setlocale) so that it works automatically, but I haven't been able to figure it out.

    Here's another way to do it:

    scan(text=testDat,dec=",",na.strings="na",quiet=TRUE)
    
    0 讨论(0)
提交回复
热议问题