小编ide*_*yst的帖子

在R中没有NA强制将字符转换为数字

我在R中工作并且有一个带有数字向量的数据帧dd_2006.当我第一次导入数据时,我需要从3个变量中删除$,小数点和一些空格:SumOfCost,SumOfCases和SumOfUnits.为此,我用过str_replace_all.但是,一旦我使用str_replace_all,矢量被转换为字符.所以我使用as.numeric(var)将向量转换为数字,但引入了NAs,即使我在运行as.numeric代码之前运行下面的代码时,向量中也没有NA.

sum(is.na(dd_2006$SumOfCost))
[1] 0
sum(is.na(dd_2006$SumOfCases))
[1] 0
sum(is.na(dd_2006$SumOfUnits))
[1] 0
Run Code Online (Sandbox Code Playgroud)

这是导入后的代码,从向量中删除$开始.在str(dd_2006)输出中,我为了空间而删除了一些变量,因此str_replace_all下面代码中的列#s 与我在此处发布的输出不匹配(但它们在原始代码中执行):

library("stringr")
dd_2006$SumOfCost <- str_sub(dd_2006$SumOfCost, 2, ) #2=the first # after the $

#Removes decimal pt, zero's after, and commas
dd_2006[ ,9] <- str_replace_all(dd_2006[ ,9], ".00", "")
dd_2006[,9] <- str_replace_all(dd_2006[,9], ",", "")

dd_2006[ ,10] <- str_replace_all(dd_2006[ ,10], ".00", "")
dd_2006[ ,10] <- str_replace_all(dd_2006[,10], ",", "")

dd_2006[ ,11] <- str_replace_all(dd_2006[ ,11], ".00", "")
dd_2006[,11] <- str_replace_all(dd_2006[,11], ",", "")

str(dd_2006)
'data.frame':   12604 obs. …
Run Code Online (Sandbox Code Playgroud)

r numeric vector character na

7
推荐指数
2
解决办法
7万
查看次数

标签 统计

character ×1

na ×1

numeric ×1

r ×1

vector ×1