Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace blank cells with character

Tags:

r

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.

like image 662
NewbieDave Avatar asked Jan 20 '14 20:01

NewbieDave


People also ask

How do you replace blank cells with value?

Alternatively, you can click the Home tab in the Ribbon and then select Go to Special from the Find & Select drop-down menu. Select Blanks in the Go To Special dialog box and click OK. Excel will select all of the blank cells within the range. Type the value you want to enter in the blanks (such as 0, – or text).

How do I replace a blank cell?

Use Excel's Find/Replace Function to Replace Zeros Choose Find/Replace (CTRL-H). Use 0 for Find what and leave the Replace with field blank (see below). Check “Match entire cell contents” or Excel will replace every zero, even the ones within values.


2 Answers

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
like image 144
Sven Hohenstein Avatar answered Sep 20 '22 15:09

Sven Hohenstein


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"
like image 32
Carlos Cinelli Avatar answered Sep 19 '22 15:09

Carlos Cinelli