如何在包含 NaN 的 R 数据框中删除行?
NaN 值在 R 中被称为“非数字”。它也被称为未定义或不可表示,但它属于数字数据类型,表示非数字值,尤其是在浮点算术中。要删除包含 NaN 的 R 中数据框的行,我们可以使用 na.omit 函数。
示例 1
考虑以下数据框 −
x1<−sample(c(NaN,5,10),20,replace=TRUE) x2<−sample(c(NaN,0,1),20,replace=TRUE) df1<−data.frame(x1,x2) df1
输出
x1 x2 1 NaN NaN 2 10 0 3 NaN NaN 4 NaN NaN 5 NaN NaN 6 NaN NaN 7 5 1 8 5 1 9 5 NaN 10 10 NaN 11 5 NaN 12 NaN NaN 13 NaN NaN 14 NaN NaN 15 10 1 16 10 0 17 NaN NaN 18 NaN 1 19 NaN NaN 20 5 1
从 df1 中删除包含 NaN 的行 −
df1<−na.omit(df1) df1
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
x1 x2 2 10 0 7 5 1 8 5 1 15 10 1 16 10 0 20 5 1
示例 2
y1<−sample(c(NaN,rnorm(5)),20,replace=TRUE) y2<−sample(c(NaN,rnorm(2)),20,replace=TRUE) df2<−data.frame(y1,y2) df2
输出
y1 y2 1 0.71997269 NaN 2 0.31324492 NaN 3 0.71997269 −0.1903841 4 1.23101131 −0.1903841 5 0.09512564 −0.1903841 6 0.71997269 0.3998648 7 −0.14221014 −0.1903841 8 0.09512564 NaN 9 NaN NaN 10 1.23101131 0.3998648 11 −0.14221014 0.3998648 12 1.23101131 NaN 13 NaN 0.3998648 14 0.71997269 NaN 15 0.09512564 NaN 16 0.31324492 NaN 17 NaN NaN 18 0.09512564 0.3998648 19 1.23101131 0.3998648 20 0.71997269 −0.1903841
从 df2 中删除包含 NaN 的行 −
示例
df2<−na.omit(df2) df2
输出
y1 y2 3 0.71997269 −0.1903841 4 1.23101131 −0.1903841 5 0.09512564 −0.1903841 6 0.71997269 0.3998648 7 −0.14221014 −0.1903841 10 1.23101131 0.3998648 11 −0.14221014 0.3998648 18 0.09512564 0.3998648 19 1.23101131 0.3998648 20 0.71997269 −0.1903841
广告