I wrote a function that perfectly replaces custom values of a matrix with NA.
NAfun <- function (x, z) {
x[x %in% z] <- NA
x
}
M <- matrix(1:12, 3, 4)
M[1, 2] <- -77
M[2, 1] <- -99
> M
[,1] [,2] [,3] [,4]
[1,] 1 -77 7 10
[2,] -99 5 8 11
[3,] 3 6 9 12
z <- c(-77, -99)
> NAfun(M, z)
[,1] [,2] [,3] [,4]
[1,] 1 NA 7 10
[2,] NA 5 8 11
[3,] 3 6 9 12
But this won't work with data frames.
D <- as.data.frame(matrix(LETTERS[1:12], 3, 4))
> D
V1 V2 V3 V4
1 A D G J
2 B E H K
3 C F I L
z <- c("B", "D")
> NAfun(D, z)
V1 V2 V3 V4
1 A D G J
2 B E H K
3 C F I L
D[] <- lapply(D, function(x) as.character(x)) # same with character vectors
> NAfun(D, z)
V1 V2 V3 V4
1 A D G J
2 B E H K
3 C F I L
If I convert the data frame to a matrix it works, though.
> NAfun(as.matrix(D), z)
V1 V2 V3 V4
[1,] "A" NA "G" "J"
[2,] NA "E" "H" "K"
[3,] "C" "F" "I" "L"
But I can't in my case.
I don't understand why this won't work as it is. And which way to adapt the function so that it works with a data frame, or preferably both types, thanks.