Hello everybody!
I have got two files, which contain a lot of values. In this example they have been greatly shortened.
The first one is a SpatialPointsDataFrame (spatial1) with 6 observations of one variable (class):
class(spatial1)
# [1] "SpatialPointsDataFrame"
# attr(,"package")
# [1] "sp"
spatial1
# class
# 1 9
# 2 9
# 3 8
# 4 8
# 5 8
# 6 9
The second one is a matrix (matrix1) with six rows and three columns and with some NA values:
class(matrix1)
# [1] "matrix" "array"
matrix1
# S1 S2 S5
# [1,] 35 45 51
# [2,] 34 32 62
# [3,] 61 58 69
# [4,] 27 51 NA
# [5,] 37 72 25
# [6,] NA NA NA
I would like identify the rows in matrix1 which contain ANY NA values and then I would like to remove those rows in matrix1 but also the corresponding rows in spatial1. "Corresponding" means here "same index/position".
Because row 4 and 6 of matrix1 contain NA, my solution should look like this:
spatial2
# class
# 1 9
# 2 9
# 3 8
# 5 8
matrix2
# S1 S2 S5
# [1,] 35 45 51
# [2,] 34 32 62
# [3,] 61 58 69
# [5,] 37 72 25
I managed removing the rows in matrix1 with this code:
matrix2 <- na.omit(matrix1)
But I found it difficult to remove the corresponding rows in spatial1, because first I have to identify which rows in matrix1 contain values with NA ββand then, with this knowledge, I have to remove the rows in spatial1.
To identify which rows of matrix1 contain any NA values I tried this:
matrix1_truefalse <- matrix1[rowSums(is.na(matrix1)) > 0,]
matrix1_truefalse
# [1] FALSE FALSE FALSE TRUE FALSE TRUE
It tells me correctly that row 4 and 6 contain NA. But how can I use this knowledge to remove the rows in spatial1?
spatial2 <- spatial1[??????matrix1_truefalse??????, ]
Please consider, that my real data is very big. So I can't just type spatial2 <- spatial1[c(1,2,3,5),].