如何在R中将百分比字符转换为数字 [英] How to convert character of percentage into numeric in R

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

问题描述

将百分比字符转换为数字时遇到问题。例如。我想将 10%转换为10%,但是

I run into a problem when converting character of percentage to numeric. E.g. I want to convert "10%" into 10%, but

as.numeric("10%")

返回 NA 。您有任何想法吗?

returns NA. Do you have any ideas?

推荐答案

10%的定义不是数字矢量。因此,答案NA是正确的。您可以通过以下方式将包含这些数字的字符向量转换为数字:

10% is per definition not a numeric vector. Therefore, the answer NA is correct. You can convert a character vector containing these numbers to numeric in this fashion:

percent_vec = paste(1:100, "%", sep = "")
as.numeric(sub("%", "", percent_vec))

这是通过使用sub将%字符替换为空而实现的。

This works by using sub to replace the % character by nothing.

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

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