我的数字为“,”为1000以上,R认为是因素。我想将两个这样的变量从因子切换到数字(实际上两个变量都是数字,但是R由于某种原因将它们视为因子(数据在excel中)。要将两个因子变量(rcffull$Returning.Backers
和rcffull$New.Backers
)更改为数值变量,我使用下面的代码,但它似乎没有正常工作,一些值改变,例如它将8180更改为零!它也发生了许多其他值。还有其他方法没有这样的ssues吗?
rcffull$RetBackers <- as.numeric(as.character(rcffull$Returning.Backers))
rcffull$NewBackers <- as.numeric(as.character(rcffull$New.Backers))
由于问题似乎是您已将数字数据保存为Excel中的字符(而不是使用格式来显示逗号),您可能需要这样的函数。
#' Replace Commas Function
#'
#' This function converts a character representation of a number that contains a comma separator with a numeric value.
#' @keywords read data
#' @export
replaceCommas<-function(x){
x<-as.numeric(gsub("\\,", "", x))
}
然后
rcffull$RetBackers <- replaceCommas(rcffull$Returning.Backers)
rcffull$NewBackers <- replaceCommas(rcffull$New.Backers)
G5W要求dput
输出的原因是他(我们)无法确定哪些东西显示为8180
,因为它可能无法正确转换为该代码。这不是因为前导空格或尾随空格(不会出现在print
版本的因子中。见证此测试:
> as.numeric(as.character(factor(" 8180")))
[1] 8180
> as.numeric(as.character(factor(" 8180 ")))
[1] 8180
并且它被转换为0的事实是一个真正的难题,因为通常不被识别为可解析的R数字的项目将被强制转换为NA(带有警告)。
> as.numeric(as.character(factor(" 0 8180 ")))
[1] NA
Warning message:
NAs introduced by coercion
我们真的需要显示为“8180”及其邻居的项目的dput
输出。