将带有%的百分比列转换为R中的数字 [英] Convert percentage columns with % into numeric in R

查看:92
本文介绍了将带有%的百分比列转换为R中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的数据集,如下所示:

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%

我想将 month_pct year_pct (它们是因子类型)转换为数字,然后乘以 100 .

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

我如何在R中做到这一点?谢谢.

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

参考代码:

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

推荐答案

第一个解决方案:您可以使用 reader 中的 parse_number .

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

第二种解决方法:

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

这篇关于将带有%的百分比列转换为R中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆