1

I Have 2 indicator:

       licence     age.6-17
         Na         1
         1          0
         Na         0
         0          1

how I can change Na to 1 if a person is more than 17 years (that is second column is 0) old and 0 otherwise?

output

       licence     age.6-17
         0          1
         1          0
         1          0
         0          1
shere
  • 245
  • 1
  • 8

3 Answers3

2

using dplyr and ifelse

yourdata %>% mutate(licence = ifelse(`age.6-17` == 0, 1,0)) 

No need to change how the nature of "Na" nor the column name.

In addition, in case you would need to replace only the "Na" cells, considering "Na" is a string here

yourdata %>% mutate(licence = ifelse(licence == "Na" & `age.6-17` == 0, 1,0)) 

If however it is <NA> you would need is.na(licence) instead of licence == "Na"

tom
  • 695
  • 3
  • 16
2

In base you can subset with is.na and then subtract the value of age.6.17 from 1.

x  <- read.table(header=T, na.string="Na", text="licence     age.6-17
         Na         1
         1          0
         Na         0
         0          1")

idx <- is.na(x$licence)
x$licence[idx]  <- 1-x$age.6.17[idx]
x
#  licence age.6.17
#1       0        1
#2       1        0
#3       1        0
#4       0        1

or in case you ignore what is actualy stored in column licence you can use:

with(x, data.frame(licence=1-age.6.17, age.6.17))
#  licence age.6.17
#1       0        1
#2       1        0
#3       1        0
#4       0        1
GKi
  • 20,626
  • 1
  • 11
  • 24
1

Assuming your NAs are actual NA we can use case_when in dplyr and apply the conditions.

library(dplyr)

df %>%
  mutate(licence = case_when(is.na(licence) & age.6.17 == 0 ~ 1L, 
                             is.na(licence) & age.6.17 == 1 ~ 0L, 
                             TRUE ~ licence))

#  licence age.6.17
#1       0        1
#2       1        0
#3       1        0
#4       0        1

data

df <- structure(list(licence = c(NA, 1L, NA, 0L), age.6.17 = c(1L, 
0L, 0L, 1L)), class = "data.frame", row.names = c(NA, -4L))
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143