简体   繁体   English

R:将 gsub 应用于数据帧会返回 NA

[英]R: Applying gsub to data frames returns NAs

I am trying to convert a data frame that contains numbers and blanks to numeric.我正在尝试将包含数字和空格的数据框转换为数字。 Currently, numbers are in factor format and some have ",".目前,数字采用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

Remove "," and convert to numeric format:删除“,”并转换为数字格式:

df2 = as.numeric(gsub(",","",df))
Warning message:
NAs introduced by coercion

Interestingly, if I perform the same function column by column, it worked:有趣的是,如果我逐列执行相同的功能,它会起作用:

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

My questions are 1. What is the cause and if there is a way to avoid converting them column by column since the actual data frame has lots more columns;我的问题是 1. 原因是什么,是否有办法避免逐列转换它们,因为实际数据框有更多列; and 2. What would be the best way to remove NAs or replace them by 0s for future numeric operations?和 2. 删除 NAs 或将它们替换为 0 以用于未来的数字运算的最佳方法是什么? I know I can use gsub to do so but just wondering if there is a better way.我知道我可以使用gsub来这样做,但只是想知道是否有更好的方法。

We can use replace_na after replace the , with '' ( str_replace_all )我们可以使用replace_na更换后,''str_replace_all

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

The issue with gsub/sub is that it works on vector as described in the ?gsub gsub/sub的问题在于它适用于?gsub描述的vector

x, text - a character vector where matches are sought, or an object which can be coerced by as.character to a character vector. x, text - 寻找匹配的字符向量,或者可以被 as.character 强制转换为字符向量的对象。 Long vectors are supported.支持长向量。

We can loop over the columns, apply the gsub , and assign the output back to the original dataset我们可以遍历列,应用gsub ,并将输出分配回原始数据集

df[] <- lapply(df, function(x) as.numeric(gsub(",", "", x))) 
df[is.na(df)] <- 0 # change the NA elements to 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM