Reputation: 141
I seem to have stumbled upon a predicament in my efforts to learn using R. I have a dataset that looks like this:
col1 / col2 / col3 NA / 1 / 2 1 / NA /2
What I need to do is replace everything that IS NOT NA with another value (see below)
Col1 / col2 / col 3 NA / Data / Data Data / NA/ Data
I've looked everywhere on the web, it seems that everybody wants to replace NA
's with other values, I on the other hand need the exact opposite but was unable to find any command. I even looked into "IF's" but was only able to find functions that replace values if they are eiter <
or =
or >
to a certain number. I need something that will specify..."IF different from NA
, then replace with...."
Upvotes: 1
Views: 1987
Reputation: 81683
The data:
dat <- data.frame(col1 = c(NA, 1), col2 = c(1, NA), col3 = c(2, 2))
To choose all values that are not NA
, use the logical operator !
("not") together with is.na
:
dat[!is.na(dat)] <- "Data"
col1 col2 col3
1 <NA> Data Data
2 Data <NA> Data
The same can also be achieved with the replace
function:
replace(dat, !is.na(dat), "Data")
Another approach is needed if you want to replace the values of factors. This can be achieved with the following command:
replace(data.frame(lapply(dat, as.character), stringsAsFactors = FALSE),
!is.na(dat), "Data")
Upvotes: 3