Hello I have a dataframe such as:
COL1 COL2 COL3
A 12 32
B NA NA
C NA NA
D 0 NA
E 21 90
F 0 NA
and I would like to replace all COL2
values by NA
where COL3
value is NA
Here I should get
COL1 COL2 COL3
A 12 32
B NA NA
C NA NA
D NA NA
E 21 90
F NA NA
So far I tried:
df$COL2[is.na(df$COL3)] <- NA
but it does not seem to work
Try this:
library(tidyverse)
df %>% mutate(COL2 = ifelse(is.na(COl3), NA, COL2))
# your data
COL1 <- c("A","B","C","D","E","F")
COL2 <- c(12, NA, NA, 0, 21, 0)
COL3 <- c(32, NA, NA, NA, 90, NA)
# create df
df <- cbind.data.frame(COL1, COL2, COL3)
# replacing COL2 with NA when COL3 = NA
df$COL2 <- ifelse(is.na(df$COL3), df$COL3, df$COL2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.