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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With