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

后端 未结 4 1829
我寻月下人不归
我寻月下人不归 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:29

    This is similar to Matt's answer, but it is vectorized (no loop over the rows needed). It further combines Procrastinatus Maximus' approach to treat several columns, and it also works if the values are originally stored as factors:

    df1[3:ncol(df1)] <- apply(df1[3:ncol(df1)], 2, function(x) 
                             as.numeric(gsub("(", "-", gsub(")", "", gsub("$", "",
                             as.character(x), fixed=TRUE)), fixed=TRUE)))
    #> df1
    #  id   desc price price2
    #1  0  apple  1.00  -5.90
    #2  1 banana -2.25   2.39
    #3  2 grapes  1.97  -0.95
    

    data

    df1 <- structure(list(id = 0:2, desc = structure(1:3, .Label = c("apple", 
             "banana", "grapes"), class = "factor"), price = structure(c(1L, 3L, 2L),
             .Label = c("$1.00", "$1.97", "($2.25)"), class = "factor"), 
             price2 = structure(c(3L, 2L, 1L), 
             .Label = c("($0.95)", "$2.39", "($5.90"),
             class = "factor")), .Names = c("id", "desc", "price", "price2"),
             class = "data.frame", row.names = c("1", "2", "3"))
    

提交回复
热议问题