I have a data frame in R:
a b c d e
1 2 3 23 1
4 5 6 -Inf 2
7 8 9 2 8
10 11 12 -Inf NaN
and I'd like to replace all the values in column e with NA if the corresponding value in column d is -Inf like this:
a b c d e
1 2 3 23 1
4 5 6 -Inf NA
7 8 9 2 8
10 11 12 -Inf NA
Any help is appreciated. I haven't been able to do it without loops, and its taking a long time for the full data frame.
ifelse
is vectorize. We can use ifelse
without using a loop.
dat$e <- ifelse(dat$d == -Inf, NA, dat$e)
DATA
dat <- read.table(text = "a b c d e
1 2 3 23 1
4 5 6 -Inf 2
7 8 9 2 8
10 11 12 -Inf NaN", header = TRUE)
Using data.table
library(data.table)
setDT(dat)[is.infinite(d), e := NA]
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.