DataTable in R, formatting rows with specific value category to a percentage

前端 未结 1 1511
囚心锁ツ
囚心锁ツ 2021-01-16 20:37

If I have a datatable and my goal is to change any rows containing MONTH=\"Percent Change:\" to percentage:

             MONTH YEAR                    Client         


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

    We can convert the columns 4 to 8 as character class. Then, using the logical condition in i, we loop over the columns 4 to 8, paste the % and assign (:=) it back to the columns.

    library(data.table)
    setDT(df)[, (4:8) := lapply(.SD, as.character), .SDcols= 4:8]
    df[MONTH=="Percent Change:", (4:8) := 
        lapply(.SD, function(x) paste0(x[!is.na(x)],"%")), .SDcols=4:8]
    
    0 讨论(0)
提交回复
热议问题