简体   繁体   中英

R empty string replacement

I should convert 'N/A' and 'not known' to a blank string “”

   Var1     Freq
1  N/A       650
2  NONE      264
3  NOT KNOWN  58

to be like this

Var1  Freq
1      650
2      264
3      58

and

"" <- new_building[grepl("N/A|NOT|KNOWN", new_building$Var1),]

I used this but this is not working

> string<-'asdaN/A'
> string2<-gsub(string,pattern='N/A',replacement='')
> string2
 [1] "asda"

do you mean this?

Edit: following updated q:

string<-c('Var1','Freq', '1','N/A','650','2', 'NONE','264', '3', 'NOT KNOWN', '58')
string[!string%in%'N/A']

how about this:

df_ <- data.frame(Var1 = c('N/A', 'NONE', 'NOT KNOWN'), Freq = c(650, 264, 58))

df_$Var1 <- gsub("N/A|NONE|NOT KNOWN", "", df_$Var1)
df_

#  Var1 Freq
#1       650
#2       264
#3        58

your assignment to "" ( "" <- ... ) is very wrong; i am not sure what your logic is here. the correct approach is to substitute strings satisfying your criteria with empty strings "" using gsub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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