如何在R中只用空格("")替换单元格

时间:2016-11-03 11:48:51

标签: r replace gsub

我正在尝试用R中的空格("")替换单元格,但由于某种原因它无效。我的矢量是这样的:

[1] "SICREDI N/NE"            "SICOOB CREDIMINAS"       "UNICRED SC/PR"          
[4] " "                       " "                       "CRESOL  SC/RS"          

我尝试使用CENTRAL<-gsub("\\\b \\\b", NA,CENTRAL) 但后来又回来了:

[1] NA              NA              NA              NA              NA             
[6] "CRESOL  SC/RS" NA              NA              NA              NA 

2 个答案:

答案 0 :(得分:4)

你的单词中有空格,所以gsub插入一个NA,导致整个条目中的NA值。你可以这样做:

vec <- c("words with spaces", "word with spaces", " ", " ", "not", "here")
vec

[1] "words with spaces"
[2] "word with spaces" 
[3] " "                
[4] " "                
[5] "not"              
[6] "here"    


vec[vec==" "]
[1] " " " "

vec[vec==" "] <- NA
vec
[1] "words with spaces"
[2] "word with spaces" 
[3] NA                 
[4] NA                 
[5] "not"              
[6] "here"

答案 1 :(得分:2)

更快的方法可能是(加布里埃尔打败了我):

x <- c("SICREDI N/NE", "SICOOB CREDIMINAS", "UNICRED SC/PR",
       " ", " ", "CRESOL SC/RS")
x[x == " "] <- NA

你正在用正则表达式做什么,但速度相当慢(以毫秒为单位测量超过40,000个元素)

x <- rep(c("SICREDI N/NE", "SICOOB CREDIMINAS", "UNICRED SC/PR",
       " ", " ", "CRESOL SC/RS"), 10000)

y <- rep(c("SICREDI N/NE", "SICOOB CREDIMINAS", "UNICRED SC/PR",
       " ", " ", "CRESOL SC/RS"), 10000)

z <- rep(c("SICREDI N/NE", "SICOOB CREDIMINAS", "UNICRED SC/PR",
           " ", " ", "CRESOL SC/RS"), 10000)

library(microbenchmark)
microbenchmark(
  first = {x[x == " "] <- NA},
  second = {y[grepl("^\\b \\b$", y)] <- NA},
  sub = gsub("^\\b \\b$", NA, z)
)

Unit: milliseconds
   expr       min        lq      mean    median        uq       max neval cld
  first  1.223415  1.231626  1.367973  1.235438  1.247461  2.896081   100 a  
 second  5.633810  5.681902  5.929447  5.697737  5.742457  8.063632   100  b 
    sub 16.960371 17.223557 17.345403 17.271795 17.308452 18.919242   100   c

作为一个观点,我发现x[x == " "] <- NA比任何一种正则表达式方法都更容易阅读。

如果您希望略微提高速度,可以使用x[x %in% " "] <- NA,这比==更有效,但只能勉强。

(现在我已经正式花了太多时间探索这个:))