[R] how to delete columns with NA values?
Erik Iverson
eriki at ccbr.umn.edu
Wed Apr 14 17:08:12 CEST 2010
Hello,
muting wrote:
> Hi everyone:
>
> I have a dataset:
This looks like a matrix. To perform functions on each row or column of
a matrix, use the apply function.
If you had a data.frame, you could perform a function on each column
using sapply or lapply.
>
> tm1
> col1 col2
> [1,] 1 NA
> [2,] 1 1
> [3,] 2 2
> [4,] 1 1
> [5,] 2 2
> [6,] 1 NA
>
> I need to delete entire column 2 that has NA in it(not all of them are NAs),
> and the result I want is
>
> tm1
> col1
> [1,] 1
> [2,] 1
> [3,] 2
> [4,] 1
> [5,] 2
> [6,] 1
>
> what should I do?
## for a data.frame x
x <- data.frame(a = 1:10, b = c(2:10, NA), c = 2:11)
x[sapply(x, function(x) !any(is.na(x)))]
## for a matrix y
y <- matrix(1:30, ncol = 3)
y[20] <- NA
y[, apply(y, 2, function(x) !any(is.na(x)))]
## or maybe even simply...
y[,complete.cases(t(y))]
More information about the R-help
mailing list