R change $xxx.xx to xxx.xx for both positive and negative numbers but don't round

后端 未结 4 1777
我寻月下人不归
我寻月下人不归 2021-01-22 20:36

I have a df where columns 2 and beyond are dollar amounts such as $1004.23, ($1482.40), $2423.94 etc. Similar to the example below:

> df
  id   desc    price
         


        
4条回答
  •  鱼传尺愫
    2021-01-22 21:20

    I might approach this more like the following:

    dat <- read.table(text = "id   desc    price
    1  0    apple   $1.00
    2  1    banana  ($2.25)
    3  2    grapes  $1.97",sep = "",header = TRUE,stringsAsFactors = FALSE)
    
    dat$neg <- ifelse(grepl("^\\(.+\\)$",dat$price),-1,1)
    dat$price1 <- with(dat,as.numeric(gsub("[^0-9.]","",price)) * neg)
    
    > dat
      id   desc   price neg price1
    1  0  apple   $1.00   1   1.00
    2  1 banana ($2.25)  -1  -2.25
    3  2 grapes   $1.97   1   1.97
    

    ...where if you're doing this for multiple columns, you probably wouldn't store the +/- info in the data frame each time, but you get the basic idea.

提交回复
热议问题