是否有一个R函数用于将列中的选择值从字符更改为整数



我在R中有一个df,其中一列表示ID号(例如,13042039等(。这是一个非常大的数据集,一个特定的行包含一个用字符写出来的ID号(如,二千三十二(。当我将列中的所有值从字符转换为整数时,文本值现在表示为N/A。有没有办法将这一个文本值重新编码为其各自的整数(2032(?

我在Excel中做了一个快速修复,但想知道R代码是什么来处理这个问题以备将来使用。

'wordstonumbers'包将拼写出来的数字转换为"数字";。

我试图用数字和字符转换矢量,但没有成功。所以我创建了这个函数来完成这项工作。

OBS.:显然,只有英语才能将单词转换为数字。。。

#library(devtools)
#devtools::install_github("fsingletonthorn/words_to_numbers")
library(wordstonumbers)
# example
n <- c(1, 304, 2039, "two thousand thirty two")
number <- function(vector){
b <- NULL
for(i in 1:length(vector)){
if(is.na(as.numeric(vector[i]))==T){
b[i] <- words_to_numbers(vector[i])
}else{
b[i] <- as.numeric(vector[i])
}
}
b <- as.numeric(b)
return(b)
}
number(n)

dat <- data.frame(ID = c(1, 304, 2039, "two thousand thirty two"))

如果您想手动替换单个值,在基本R中,您可以使用

dat$ID[dat$ID == "two thousand thirty two"] <- 2032

使用dplyr

library(dplyr)
dat_new <- dat |> mutate(ID = replace(ID, ID == "two thousand thirty two", 2032))

这并不理想,因为你要对字符串及其整数等价物进行硬编码,但它比在Excel中修复它要好,因为它允许记录和复制这个数据清理步骤。

最新更新