Convert percentage columns with % into numeric in R

為{幸葍}努か 提交于 2021-02-16 15:29:12

问题


I have a small dataset as follows:

   id  price month_pct year_pct
0   1   1.85    -2.63%   -5.13%
1   2   2.42     0.00%    0.83%
2   3   1.81     0.00%   -0.55%
3   4   4.37    -2.89%   -5.62%
4   5   1.86     0.00%   -7.92%
5   6   1.78    -1.11%  -15.24%

I would like to convert month_pct and year_pct (which are factor type) into numeric then multiply by 100.

How could I do that in R? Thanks.

   id  price month_pct year_pct
0   1   1.85    -2.63   -5.13
1   2   2.42     0.00    0.83
2   3   1.81     0.00   -0.55
3   4   4.37    -2.89   -5.62
4   5   1.86     0.00   -7.92
5   6   1.78    -1.11  -15.24

Code for reference:

df$month_pct <- as.numeric(sub("%", "", df$month_pct))/100 

回答1:


1st solution: you can use parse_number from readr.

library(dplyr)
df %>% mutate(across(month_pct:year_pct, ~readr::parse_number(.x) * 100))


#  id price month_pct year_pct
#1  1  1.85      -263     -513
#2  2  2.42         0       83
#3  3  1.81         0      -55
#4  4  4.37      -289     -562
#5  5  1.86         0     -792
#6  6  1.78      -111    -1524

2rd solution:

cols = c('month_pct', 'year_pct')
df[cols] <- lapply(df[cols], function(x) as.numeric(sub('%', '', x)) * 100)



回答2:


tochange <- endsWith(names(df),"pct")
df[tochange] = as.numeric(sub("%", "", as.matrix(df[tochange]))) * 100

 df
  id price month_pct year_pct
0  1  1.85      -263     -513
1  2  2.42         0       83
2  3  1.81         0      -55
3  4  4.37      -289     -562
4  5  1.86         0     -792
5  6  1.78      -111    -1524


来源:https://stackoverflow.com/questions/62527728/convert-percentage-columns-with-into-numeric-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!