我在表中有正值,负值和NA
值,我需要用NA
值替换负值。正值和NA
值应保持在表中。我的数据集类似于下面的数据集:
NO. q
1 NA
2 NA
3 -133.6105198
4 -119.6991209
5 28.84460104
6 66.05345087
7 84.7058947
8 -134.4522694
9 NA
10 NA
11 73.20465643
12 -69.90723514
13 NA
14 69.70833003
15 65.27859906
我试过了:
if (q>0) {
q=NA
} else {
q=q
}
答案 0 :(得分:5)
或使用replace
:
> df$q2 <- replace(df$q, which(df$q < 0), NA)
> df
NO. q q2
1 1 NA NA
2 2 NA NA
3 3 -133.61052 NA
4 4 -119.69912 NA
5 5 28.84460 28.84460
6 6 66.05345 66.05345
7 7 84.70589 84.70589
8 8 -134.45227 NA
9 9 NA NA
10 10 NA NA
11 11 73.20466 73.20466
12 12 -69.90724 NA
13 13 NA NA
14 14 69.70833 69.70833
15 15 65.27860 65.27860
或者使用data.table:
library(data.table)
setDT(df)[q < 0, q := NA]
或者在dplyr管道中替换:
library(dplyr)
df %>% mutate(q = replace(q, which(q<0), NA))
答案 1 :(得分:5)
你可以试试这个:
sample <- c(1, -2, NA)
sample[sample < 0] <- NA
sample
[1] 1 NA NA
或者,如果您使用的是data.frame
(假设它名为df
):
df$q[df$q < 0] <- NA
答案 2 :(得分:4)
你可以尝试
df1$q1 <- NA^(df1$q <0) * df1$q
df1
# NO. q q1
#1 1 NA NA
#2 2 NA NA
#3 3 -133.61052 NA
#4 4 -119.69912 NA
#5 5 28.84460 28.84460
#6 6 66.05345 66.05345
#7 7 84.70589 84.70589
#8 8 -134.45227 NA
#9 9 NA NA
#10 10 NA NA
#11 11 73.20466 73.20466
#12 12 -69.90724 NA
#13 13 NA NA
#14 14 69.70833 69.70833
#15 15 65.27860 65.27860
或使用ifelse
with(df1, ifelse(q < 0, NA, q))
或者
is.na(df1$q) <- df1$q < 0
答案 3 :(得分:1)
另一种完成同样事情的方法是(现在我看到这几乎与akrun的另一个答案相同,对不起)
daf$q = ifelse(daf$q < 0, NA_real_, daf$q)