Re: [R] unexpected behavior in apply

2021-10-13 Thread Derickson, Ryan, VHA NCOD via R-help
ter. But I appreciate the explanation and the solutions. -Original Message- From: PIKAL Petr Sent: Monday, October 11, 2021 5:15 AM To: Jiefei Wang ; Derickson, Ryan, VHA NCOD Cc: r-help@r-project.org Subject: [EXTERNAL] RE: [R] unexpected behavior in apply Hi it is not surpr

Re: [R] unexpected behavior in apply

2021-10-11 Thread Rolf Turner
On Mon, 11 Oct 2021 09:15:27 + PIKAL Petr wrote: > > data.frame is not matrix or array (even if it rather resembles one) > > So if you put a cake into oven you cannot expect getting fried > potatoes from it. Another fortune nomination! cheers, Rolf -- Honorary Research Fellow Depar

Re: [R] unexpected behavior in apply

2021-10-11 Thread PIKAL Petr
SE Cheers Petr > -Original Message- > From: R-help On Behalf Of Jiefei Wang > Sent: Friday, October 8, 2021 8:22 PM > To: Derickson, Ryan, VHA NCOD > Cc: r-help@r-project.org > Subject: Re: [R] unexpected behavior in apply > > Ok, it turns out that this is doc

Re: [R] unexpected behavior in apply

2021-10-08 Thread Jiefei Wang
Ok, it turns out that this is documented, even though it looks surprising. First of all, the apply function will try to convert any object with the dim attribute to a matrix(my intuition agrees with you that there should be no conversion), so the first step of the apply function is > as.matrix.da

Re: [R] unexpected behavior in apply

2021-10-08 Thread Andrew Simmons
Hello, The issue comes that 'apply' tries to coerce its argument to a matrix. This means that all your columns will become character class, and the result will not be what you wanted. I would suggest something more like: sapply(d, function(x) all(x[!is.na(x)] <= 3)) or vapply(d, function(x) a

Re: [R] unexpected behavior in apply

2021-10-08 Thread Jiefei Wang
Hi, I guess this can tell you what happens behind the scene > d<-data.frame(d1 = letters[1:3], + d2 = c(1,2,3), + d3 = c(NA,NA,6)) > apply(d, 2, FUN=function(x)x) d1 d2 d3 [1,] "a" "1" NA [2,] "b" "2" NA [3,] "c" "3" " 6" > "a"<=3 [1] FALSE > "2"<=3 [1] TRUE >

[R] unexpected behavior in apply

2021-10-08 Thread Derickson, Ryan, VHA NCOD via R-help
Hello, I'm seeing unexpected behavior when using apply() compared to a for loop when a character vector is part of the data subjected to the apply statement. Below, I check whether all non-missing values are <= 3. If I include a character column, apply incorrectly returns TRUE for d3. If I onl