我有一个通过读取具有以下属性的 csv 文件创建的数据框:
'data.frame': 1290 obs. of 9 variables:
$ Date : Factor w/ 1290 levels "1/3/2020 00:00",..: 97 98 99 100 101 102 103 104 105 106 ...
$ Moisture.20.0 : num 39.8 40 40.1 40.1 40.2 ...
$ Moisture.46.0 : num 40.9 40.9 40.9 40.9 40.9 ...
$ Temperature.20.0: num 32.6 32.7 33 33.4 33.7 ...
$ Temperature.46.0: num 32.3 31.9 31.9 31.8 31.8 ...
$ EC.20.0 : num 0.302 0.303 0.305 0.309 0.313 ...
$ EC.46.0 : num 0.511 0.507 0.507 0.507 0.507 ...
$ Field.ID : int 6466 6466 6466 6466 6466 6466 6466 6466 6466 6466 ...
$ Sensor.loc : Factor w/ 1 level "-00.0000000 00.0000000": 1 1 1 1 1 1 1 1 1 1
你可以看到它有 9 个变量的 1290 行。
但是,当我继续确定数据集中是否有任何 NA 值时,我得到TRUE
.
any(is.na(df))
[1] TRUE
我知道这个特定的 csv 没有 NA 的事实。此外,我使用该which()
函数来确定我可以在数据框中的哪个位置找到 NA 但得到奇怪的结果:
which(is.na(df))
[1] 1799 6959
如果我理解正确,调用将返回两个索引值,我将在其中找到 NA:[1799, ] 和 [6959, ]。
我不明白的是,如果我的原始数据集根据str()
函数调用只有 1290,为什么我会得到这些值。
该which()
函数是否识别不同的维度str()
?我怎么能相信which(is.na(df))
为我提供正确的索引来检查和处理 NA?
问题是 1799 不是第 1799行,而是按列排列的第 1799 个元素。
dat <- mtcars[1:4,]
dat[3,3] <- NA
dat
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 NA 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
which(is.na(dat))
# [1] 11
这 11 个包括:第 1 列中的 4 个、第 2 列中的 4 个以及第 3 列中的第 3 个元素。如果您想进行数学运算,则
isna <- which(is.na(dat))
(isna - 1) %% nrow(dat) + 1
# [1] 3 # row of the NA
(isna - 1) %/% nrow(dat) + 1
# [1] 3 # column of the NA
ind2arr <- function(ind, nr) cbind((ind-1) %% nr + 1, (ind-1) %/% nr + 1)
ind2arr(which(is.na(dat)), nrow(dat))
# [,1] [,2]
# [1,] 3 3
### demo
ind <- seq_len(prod(dim(dat)))
cbind(ind, ind2arr(ind, nrow(dat)))
# ind
# [1,] 1 1 1
# [2,] 2 2 1
# [3,] 3 3 1
# [4,] 4 4 1
# [5,] 5 1 2
# [6,] 6 2 2
# [7,] 7 3 2
# [8,] 8 4 2
# ...truncated...
# [41,] 41 1 11
# [42,] 42 2 11
# [43,] 43 3 11
# [44,] 44 4 11
或者更好的是,添加arr.ind=TRUE
以获得更好的视角。
which(is.na(dat), arr.ind = TRUE)
# row col
# Datsun 710 3 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句