我在 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
如果 d 列中的相应值是 -Inf,我想用 NA 替换 e 列中的所有值 像这样:
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
感谢任何帮助。如果没有循环,我无法做到这一点,并且需要很长时间才能获得完整的数据框。
答案 0 :(得分:3)
ifelse
是矢量化的。我们可以在不使用循环的情况下使用 ifelse
。
dat$e <- ifelse(dat$d == -Inf, NA, dat$e)
数据
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)
答案 1 :(得分:2)
使用 data.table
library(data.table)
setDT(dat)[is.infinite(d), e := NA]
答案 2 :(得分:2)