Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apply function on a matrix with NA entries

Tags:

r

I read Data from a csv file. If I see this file in R, I have:

  V1 V2  V3 V4  V5 V6 V7
1 14 25  83 64 987 45 78
2 15 65 789 32  14 NA NA
3 14 67  89 14  NA NA NA

If I want the maximum value in each column, I use this:

apply(df,2,max)

and this is the result:

 V1  V2  V3  V4  V5  V6  V7 
 15  67 789  64  NA  NA  NA 

but it works on the column that has no NA. How can I change my code, to compare columns with NA too?

like image 532
TangoStar Avatar asked Sep 16 '13 12:09

TangoStar


People also ask

How do you apply a function to each row of a matrix in R?

You can use the apply() function to apply a function to each row in a matrix or data frame in R. where: X: Name of the matrix or data frame. MARGIN: Dimension to perform operation across.

What is apply () in R?

The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained.

How do I apply a function to a list in R?

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.

How do I apply a function to a column in R?

apply() lets you perform a function across a data frame's rows or columns. In the arguments, you specify what you want as follows: apply(X = data. frame, MARGIN = 1, FUN = function.


1 Answers

You just need to add na.rm=TRUE to your apply call.

apply(df,2,max,na.rm=TRUE)

Note: This does assume every column has at least one data point. If one does not sum will return 0.

EDIT BASED ON COMMENT

fft does not have an na.rm argument. Therefore, you will need to write your own function.

apply(df,2,function(x){fft(x[!is.na(x)])})

For example:

df <- data.frame(matrix(5,5,5))
df[,3] <- NA

> df
  X1 X2 X3 X4 X5
1  5  5 NA  5  5
2  5  5 NA  5  5
3  5  5 NA  5  5
4  5  5 NA  5  5
5  5  5 NA  5  5

> apply(df,2,function(x){fft(x[!is.na(x)])})
$X1
[1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i
[5] 1.776357e-15+0i

$X2
[1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i
[5] 1.776357e-15+0i

$X3
complex(0)

$X4
[1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i
[5] 1.776357e-15+0i

$X5
[1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i
[5] 1.776357e-15+0i
like image 88
dayne Avatar answered Oct 17 '22 10:10

dayne