我有这个字符串变量
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/