Question

There is a data.frame() for which's columns I'd like to calculate quantiles:

tert <- c(0:3)/3
data <- dbGetQuery(dbCon, "SELECT * FROM tablename")
quans <- mapply(quantile, data, probs=tert, name=FALSE)

But the result only contains the last element of quantiles return list and not the whole result. I also get a warning longer argument not a multiple of length of shorter. How can I modify my code to make it work?

PS: The function alone works like a charme, so I could use a for loop:

quans <- quantile(a$fileName, probs=tert, name=FALSE)

PPS: What also works is not specifying probs

quans <- mapply(quantile, data, name=FALSE)
Was it helpful?

Solution

The problem is that mapply is trying to apply the given function to each of the elements of all of the specified arguments in sequence. Since you only want to do this for one argument, you should use lapply, not mapply:

lapply(data, quantile, probs=tert, name=FALSE)

Alternatively, you can still use mapply but specify the arguments that are not to be looped over in the MoreArgs argument.

mapply(quantile, data, MoreArgs=list(probs=tert, name=FALSE))

OTHER TIPS

I finally found a workaround which I don't like but kinda works. Perhaps someone can tell the right way to do it:

q <- function(x) { quantile(x, probs=c(0:3)/3, names=FALSE) }
mapply(q, data)

works, no Idea where the difference is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top