Reputation: 1259
I'm working on a data set that looks as follow:
191
282 A
202
210 B
I would like to replace those empty cells at the second column with a character, say 'N'. How can I efficiently do this in R?
Appreciate it.
Upvotes: 14
Views: 71504
Reputation: 1
DataFrame$FeatureName[which(DataFrame$FeatureName == "")] <- "N"
Upvotes: -1
Reputation: 11597
Another way:
Assuming the same data structure as wibeasley has put:
ds <- data.frame(ID=c(191, 282, 202, 210), Group=c("", "A", "", "B"), stringsAsFactors=FALSE)
you can just write:
ds$Group[ds$Group==""]<-"N"
Upvotes: 12
Reputation: 5287
If your data.frame is 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)
Upvotes: 4
Reputation: 81693
An example data frame:
dat <- read.table(text = "
191 ''
282 A
202 ''
210 B")
You can use sub
to replace the empty strings with "N"
:
dat$V2 <- sub("^$", "N", dat$V2)
# V1 V2
# 1 191 N
# 2 282 A
# 3 202 N
# 4 210 B
Upvotes: 23