r - 将 NA 引入 as.numeric

标签 r

我有这个字符串变量

mystr <- "98,015"

我想将其转换为数字。

所以我使用:

num <- as.numeric(mystr)

但我收到此错误:

Warning message:
NAs introduced by coercion

这里引入 NA 而不是数字。如果使用像 "21" 这样的字符串我取号成功了。我能做什么?

最佳答案

我们可以使用sub,替换为"",然后将其转换为numeric。由于 , 字符,应用 as.numeric 会将其强制为 NA。

as.numeric(sub(",", "", mystr))

如果,代表.,则将其替换为.(基于@RHertel的评论)

as.numeric(sub(",", ".", mystr))

尚不清楚OP的原始数据集是data.frame还是只是向量。如果是data.frame,使用read.csv/read.table读取时,我们可以指定dec=","

关于r - 将 NA 引入 as.numeric,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39490749/

相关文章:

r - 粘贴命名向量 R

r - 如何正确地连接R中的比迪字符串?

r - 如何正确发起 POST 请求

重新排列 R 中的数据,分解列名称

R将时间转换为一天中的时间

R 使用值作为参数将函数应用于数据框的行

r - 如何在 R 中使用 map ?

r - 使用蒙特卡罗计算圆面积

r - If 语句错误/不应用 if 语句

R Shiny switch tabPanel 当 selectInput 值改变时