A Student
A Student

Reputation: 25

R Conditional replacement of NAs based on text in another column

New to R, this has me stumped.

I have a data.frame that looks like this.

SPECIES   REST.TYPE
O         NA
O         Long
NR        NA
O         Short
NR        NA
O         NA

I want to replace the NA's in REST.TYPE with Present, but only when SPECIES = O and replace the NA's in REST.TYPE with NR when SPECIES=NR.

Required output

SPECIES   REST.TYPE
O         Present
O         Long
NR        NR
O         Short
NR        NR
O         Present

Upvotes: 1

Views: 78

Answers (1)

akrun
akrun

Reputation: 886948

We can use data.table. Convert the 'data.frame' to 'data.table' (setDT(df1)). Based on the "SPECIES" value of "O" and the NA elements in "REST.TYPE", we assign the "REST.TYPE" to "Present". Then, we assign (:=) the 'REST.TYPE' to 'SPECIES' based on the remaining NA values in 'REST.TYPE'

library(data.table)
setDT(df1)[is.na(REST.TYPE) & SPECIES=="O", REST.TYPE := "Present"]
df1[is.na(REST.TYPE), REST.TYPE := SPECIES]
df1
#   SPECIES REST.TYPE
#1:       O   Present
#2:       O      Long
#3:      NR        NR
#4:       O     Short
#5:      NR        NR
#6:       O   Present

We can also do this with base R using ifelse

with(df1, ifelse(SPECIES=="O" & is.na(REST.TYPE), "Present", 
          ifelse(is.na(REST.TYPE), SPECIES, REST.TYPE)))
#[1] "Present" "Long"    "NR"      "Short"   "NR"      "Present"

data

df1 <- structure(list(SPECIES = c("O", "O", "NR", "O", "NR", "O"), 
REST.TYPE = c(NA, 
"Long", NA, "Short", NA, NA)), .Names = c("SPECIES", "REST.TYPE"  
), class = "data.frame", row.names = c(NA, -6L))

Upvotes: 3

Related Questions