如何在R数据帧中将NaN转换为NA?
要将NaN转换为R数据帧中的NA,我们可以使用单个方括号将NaN值设置为NA值。首先,我们需要访问包含NaN值的列,然后使用访问NaN值,is.nan然后可以将这些值设置为NA,如以下示例所示。
考虑以下数据帧-
示例
x1<-sample(c(1,2,5,NaN),20,replace=TRUE)输出结果x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1
x1 x21 5 1
2 1 2
3 5 3
4 NaN 2
5 5 1
6 5 2
7 NaN 1
8 5 4
9 5 2
10 2 0
11 NaN 0
12 1 0
13 NaN 4
14 1 2
15 5 1
16 1 2
17 2 2
18 5 0
19 2 1
20 5 1
在df1的x1列中用NA替换NaN-
示例
df1$x1[is.nan(df1$x1)]<-NA输出结果df1
x1 x21 5 1
2 1 2
3 5 3
4 NA 2
5 5 1
6 5 2
7 NA 1
8 5 4
9 5 2
10 2 0
11 NA 0
12 1 0
13 NA 4
14 1 2
15 5 1
16 1 2
17 2 2
18 5 0
19 2 1
20 5 1
示例
y1<-sample(c(rnorm(2),NaN),20,replace=TRUE)输出结果y2<-rnorm(20)
y3<-rnorm(20)
df2<-data.frame(y1,y2,y3)
df2
y1 y2 y31 -0.0867355 -1.28729227 -0.20581922
2 NaN 1.11408057 0.56750161
3 NaN 0.47302790 -0.72410253
4 NaN -0.34217866 0.33855658
5 NaN -2.52516598 0.78809964
6 -0.0867355 -0.65268724 -0.04150251
7 -0.0867355 0.42845639 -0.12955272
8 -0.0867355 0.71995182 0.24011099
9 -0.0867355 0.07829339 3.10334568
10 -0.9135175 0.07250105 -0.41307585
11 -0.0867355 1.58477752 0.96751855
12 NaN -1.84389126 -0.42843257
13 -0.0867355 -0.10860452 -0.32978319
14 -0.9135175 -1.25311587 -1.07537515
15 -0.0867355 0.58514141 2.05516953
16 NaN 2.02405825 0.18098639
17 -0.9135175 0.90327161 -0.22561346
18 -0.9135175 0.81260538 -1.98065156
19 NaN -1.60608848 -1.39970818
20 NaN -0.82239927 -1.45993348
在df2的y1列中用NA替换NaN-
示例
df2$y1[is.nan(df2$y1)]<-NA输出结果df2
y1 y2 y31 -0.0867355 -1.28729227 -0.20581922
2 NA 1.11408057 0.56750161
3 NA 0.47302790 -0.72410253
4 NA -0.34217866 0.33855658
5 NA -2.52516598 0.78809964
6 -0.0867355 -0.65268724 -0.04150251
7 -0.0867355 0.42845639 -0.12955272
8 -0.0867355 0.71995182 0.24011099
9 -0.0867355 0.07829339 3.10334568
10 -0.9135175 0.07250105 -0.41307585
11 -0.0867355 1.58477752 0.96751855
12 NA -1.84389126 -0.42843257
13 -0.0867355 -0.10860452 -0.32978319
14 -0.9135175 -1.25311587 -1.07537515
15 -0.0867355 0.58514141 2.05516953
16 NA 2.02405825 0.18098639
17 -0.9135175 0.90327161 -0.22561346
18 -0.9135175 0.81260538 -1.98065156
19 NA -1.60608848 -1.39970818
20 NA -0.82239927 -1.45993348
以上是 如何在R数据帧中将NaN转换为NA? 的全部内容, 来源链接: utcz.com/z/319978.html