R:将 gsub 应用于数据帧 returns NAs
R: Applying gsub to data frames returns NAs
我正在尝试将包含数字和空格的数据框转换为数字。目前,数字采用 factor
格式,有些数字带有“,”。
df <- data.frame(num1 = c("123,456,789", "1,234,567", "1,234", ""), num2 = c("","1,012","","202"))
df
num1 num2
1 123,456,789
2 1,234,567 1,012
3 1,234
4 202
删除“,”并转换为数字格式:
df2 = as.numeric(gsub(",","",df))
Warning message:
NAs introduced by coercion
有趣的是,如果我逐列执行相同的功能,它会起作用:
df$num1 = as.numeric(gsub(",","",df$num1))
df$num2 = as.numeric(gsub(",","",df$num2))
df
num1 num2
1 123456789 NA
2 1234567 1012
3 1234 NA
4 NA 202
我的问题是 1. 原因是什么,是否有办法避免逐列转换它们,因为实际的数据框有更多的列;和 2. 删除 NA 或用 0 替换它们以用于未来的数字运算的最佳方法是什么?我知道我可以使用 gsub
来这样做,但只是想知道是否有更好的方法。
将,
替换为''
(str_replace_all
)
后,我们可以使用replace_na
library(dplyr)
library(stringr)
df %>%
mutate_all(list(~ str_replace_all(., ",", "") %>%
as.numeric %>%
replace_na(0)))
# num1 num2
#1 123456789 0
#2 1234567 1012
#3 1234 0
#4 0 202
gsub/sub
的问题在于它适用于 vector
,如 ?gsub
中所述
x, text -
a character vector where matches are sought, or an object which can be coerced by as.character to a character vector. Long vectors are supported.
我们可以遍历列,应用 gsub
,并将输出分配回原始数据集
df[] <- lapply(df, function(x) as.numeric(gsub(",", "", x)))
df[is.na(df)] <- 0 # change the NA elements to 0
我正在尝试将包含数字和空格的数据框转换为数字。目前,数字采用 factor
格式,有些数字带有“,”。
df <- data.frame(num1 = c("123,456,789", "1,234,567", "1,234", ""), num2 = c("","1,012","","202"))
df
num1 num2
1 123,456,789
2 1,234,567 1,012
3 1,234
4 202
删除“,”并转换为数字格式:
df2 = as.numeric(gsub(",","",df))
Warning message:
NAs introduced by coercion
有趣的是,如果我逐列执行相同的功能,它会起作用:
df$num1 = as.numeric(gsub(",","",df$num1))
df$num2 = as.numeric(gsub(",","",df$num2))
df
num1 num2
1 123456789 NA
2 1234567 1012
3 1234 NA
4 NA 202
我的问题是 1. 原因是什么,是否有办法避免逐列转换它们,因为实际的数据框有更多的列;和 2. 删除 NA 或用 0 替换它们以用于未来的数字运算的最佳方法是什么?我知道我可以使用 gsub
来这样做,但只是想知道是否有更好的方法。
将,
替换为''
(str_replace_all
)
replace_na
library(dplyr)
library(stringr)
df %>%
mutate_all(list(~ str_replace_all(., ",", "") %>%
as.numeric %>%
replace_na(0)))
# num1 num2
#1 123456789 0
#2 1234567 1012
#3 1234 0
#4 0 202
gsub/sub
的问题在于它适用于 vector
,如 ?gsub
x, text - a character vector where matches are sought, or an object which can be coerced by as.character to a character vector. Long vectors are supported.
我们可以遍历列,应用 gsub
,并将输出分配回原始数据集
df[] <- lapply(df, function(x) as.numeric(gsub(",", "", x)))
df[is.na(df)] <- 0 # change the NA elements to 0