Replace empty cells with a symbol

I am working on a dataset that looks like this:

191 282 A 202 210 B 

I would like to replace these empty cells in the second column with a character like "N". How can I do this effectively in R?

Appreciate it.

+7
r
source share
4 answers

Example data frame:

 dat <- read.table(text = " 191 '' 282 A 202 '' 210 B") 

You can use sub to replace empty strings with "N" :

 dat$V2 <- sub("^$", "N", dat$V2) # V1 V2 # 1 191 N # 2 282 A # 3 202 N # 4 210 B 
+11
source share

Another way:

Assuming the same data structures as wibeasley, put:

 ds <- data.frame(ID=c(191, 282, 202, 210), Group=c("", "A", "", "B"), stringsAsFactors=FALSE) 

you can simply write:

 ds$Group[ds$Group==""]<-"N" 
+7
source share

If your data.frame looks something like this.

 ds <- data.frame(ID=c(191, 282, 202, 210), Group=c("", "A", "", "B"), stringsAsFactors=FALSE) 

You can check the length of each element and replace it with "N" if the length is zero.

 ds$Group <- ifelse(nchar(ds$Group)==0, "N", ds$Group) 
+2
source share
 DataFrame$FeatureName[which(DataFrame$FeatureName == "")] <- "N" 
0
source share

All Articles