Multiple plotting operations with d_plyr - r

I discovered plyr and was playing with an example but could not understand why it does not work: I have a data frame of 10 (x,y) coordinates and want to plot these points one after the other
## Creating the data
df <- data.frame(a=rnorm(10),b=rnorm(10))
## Empty plot
plot(0, xlim=c(-2,2), ylim=c(-2,2))
## Function to be repeated
plot.pts <- function(x){
points(x$a,x$b)
}
## Magic d_plyr
d_ply(df,plot.pts)
But I get the error
Error in UseMethod("as.quoted") :
no applicable method for 'as.quoted' applied to an object of class "function"
I understood d_ply is the function to be used in that case, hence what am I doing wrong?

Because you are not really dividing the dataframe into groups based on variables, just calling a function for each row, I think a_ply suits better than d_ply:
a_ply(df,.margins = 1, .fun = plot.pts)
In your original d_ply call you passed your function where the .variables argument that tells d_ply how to group the data was supposed to be, giving you that error.

Related

(R, purrr) iteration over pairs of columns by name, one constant & one from a list

I am trying to produce a list of graphical objects (grobs), suitable for passing to gridExtra::grid.arrange (or some ggequivalent if that is easier). I have redrafted my example to eliminate multiple problems that were kindly pointed out by #MrFlick and #Ronak Shah. However, I still get the same error message:
Error in .f(.x[[i]], ...) : unused argument (NULL)
(and I don't get a single google hit for "unused argument (NULL)" r | purrr. The closest I find is unused argument (.null = NA).)
Each object is a set of four plots (plotted together) that are output as side effects from the acf or pacf functions, showing the autocorelation and autocovarience between two variables and their various lags. I am trying to write a function that will take a tsibble, a vector of independent variable column names from that tsibble, and the name of a single outcome variable (also a column in the input tsibble) and, using purrr, take the acf or pacf of the pairs of variables defined by the single name with each of the specified columns, convert the plot to a grob, and output a list of the grobs.
Here is my non-working function, acf version:
acf_grobs <- function(dat., mod_nms, outcome){
depend <- select(dat., all_of(mod_nms))
out <- map(depend, ~ grob(acf(x=cbind(.x, y))), y = dat.[[outcome]])
out
}
And a reproducible example:
library(tidyverse)
library(fpp3)
I know that this loads a lot more packages than needed for this example, but I am loading all these packages for other reasons.
aa <- 1:4
bb <- 1:4
cc <- 1:4
day <- 1:4
tb <- tibble(aa, bb, cc, day)
tsb <- as_tsibble(tb, index = day)
var_of_interest <- "aa"
mod.nms <- c("bb", "cc")
pacf_grobs(dat. = tsb, mod_nms = mod.nms, outcome = var_of_interest)
I still believe the error message is caused by my failure to pass the single argument outcome to the function argument of purrr::map correctly, though this belief is shaken because I am now passing it a different way, and still getting the same error message.

How extracting results using custom function in lapply works

I am trying to extract regression coefficients using the function below;
## customized function to return coef as matrix
cust_lm<- function(varname, data){
y<-data[,varname]
coefOLS<- as.matrix(coef(summary(lm(y~x))));
}
I want to run regression using different dependent variables (independent variable remain the same) each time with this function. I am using lapply for the same.
## artificial data
x<-rnorm(100,5,3)
ydata<-data.frame(y1=rnorm(100), y2=rnorm(100))
## running regressions together and storing as list
list<-lapply(names(ydata)[1:2], function(x) cust_lm(x, ydata))
I'm getting the desired result where list[[1]] is nothing but coef(summary(lm(ydata[,1]~x))) and list[[2]] is equal to coef(summary(lm(ydata[,2]~x))).
I have written this with the help of several SO posts sometime back. Now I want to decipher my custom function to know how it works and also I'm not very clear about lapply.
I have already created the custom function with the arguments requiring as, (varname, data) and again I'm giving cust_lm(x, data) as an argument in lapply. Is it right thing to do?
Is it right if I give, list<-lapply(names(ydata)[1:2], function(z) cust_lm(z, data)) instead?. I'm quite confused on this. Any help/resources are appreciated.
You can always try to break it down bit by bit.
The first iteration of lapply would call cust_lm('a', ydata). Let's take a look:
cust_lm('y1', ydata)
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.006170844 0.22234415 0.02775357 0.9779151
# x -0.004470560 0.03960525 -0.11287797 0.9103582
In your code, the name data is the variable name inside the function. So when you specify list<-lapply(names(ydata)[1:2], function(z) cust_lm(z, data)), R will be looking for a variable named data when the line is called. So this is wrong. Calling it with list<-lapply(names(ydata)[1:2], function(x) cust_lm(x, ydata)) is the correct answer. You can further simplify it as:
list <- lapply(names(ydata)[1:2], cust_lm, data=ydata)
This breaks down to "call cust_lm with each element of names(ydata)[1:2] in turn as first argument; use ydata for the argument named data".

Writing/applying "subtract the mean"-function to standardize regression parameters

I was trying to write and apply a seemingly easy function that would standardize my continuous regression parameters/ predictors. The reason is that I want to deal with multicollinearity.
So instead of writing x-mean(x,na.rm=T) each time, I'm looking for something more handy which does the job for me - not least because I wanted to exercize writing functions in R. ;)
So here is what I tried:
fun <- function(data.frame, x){
data.frame$x - mean(data.frame$x, na.rm=T)
}
Apparently this is not too wrong. At least it doesn't return an error message.
However, applying fun to, say, the built-in mtcars dataset and, say, the variable disp yields this error message:
#Loading the data:
data("mtcars")
fun(mtcars,x=disp) #I tried several ways, e.g. w and w/o "mtcars" in front
Warning message:
In mean.default(mtcars$x, na.rm = T) :
argument is not numeric or logical: returning NA
My guess is that it is about how I applied the function, because when I do manually what the function is supposed to do, it works perfectly.
Also, I was looking for similar questions on writing and applying such a function (also beyond the Stack Exchange universe), but I didn't find anything helpful.
Hope I didn't make a blunder due to my novice R-skills.
There is already a function in R which does what you want to do: scale().
You can just write scale(mtcars$hp, center = TRUE, scale = FALSE) which then subtracts the mean of the vector from the vector itself.
In combination with apply this is powerful; You can, for example center every column of your dataframe by writing:
apply(dataframe, MARGIN = 2, FUN = scale, center = TRUE, scale = FALSE)
Before you do that you have to make sure that this is a valid function for your column. You cannot scale factors or characters, for example.
In regards to your question: Your function should have to look like this:
fun <- function(data.frame, x){
data.frame[[x]] - mean(data.frame[[x]], na.rm=T)
}
and then when specifying the function you would have to write fun(mtcars, "hp") and specify the variable name in quotation marks. This is because of the special way the $ operator works, you cannot use a character string after it.

error with interpSpline function

I have a list of data frames, xyz, and in every data frame there are 2 numeric vectors (x and y). I want to apply the interpSpline function from package splines to x and y, but when I do :
lapply(xyz, function (x){
x%>%
interpSpline(x,y)
})
I get the following error:
Error in data.frame(x = as.numeric(obj1), y = as.numeric(obj2)) :
(list) object cannot be coerced to type 'double'
It doesn't work because interpSpline doesn't take a data frame as its first argument.
xyz <- list(data.frame(x=rnorm(10),y=rnorm(10)),
data.frame(x=rnorm(10),y=rnorm(10)))
library(splines)
sf <- function(d) with(d,interpSpline(x,y)))
s <- lapply(xyz,sf)
You could also use interpSpline(d$x,d$y). It might be possible to do enough contortions to get interpSpline to work with pipes, but it hardly seems worth the trouble ...
Per your comment on Ben's answer, interpSpline() requires the input x values to be unique. So, to avoid this error you could use the spline() function instead of interpSpline(). This will set s equal to the interpolated values of the spline at each x,y input coordinate. However, you will not have all the other output that you get from interpSpline().
set.seed(1)
# fake up some data that has duplicate 'x' values
xyz <- list(data.frame(x=round(rnorm(100),1),y=round(rnorm(100),1)),
data.frame(x=round(rnorm(100),1),y=round(rnorm(100),1)))
library(splines)
sf <- function(d) with(d,spline(x,y))
s <- lapply(xyz,sf)

R: passing by parameter to function and using apply instead of nested loop and recursive indexing failed

I have two lists of lists. humanSplit and ratSplit. humanSplit has element of the form::
> humanSplit[1]
$Fetal_Brain_408_AGTCAA_L001_R1_report.txt
humanGene humanReplicate alignment RNAtype
66 DGKI Fetal_Brain_408_AGTCAA_L001_R1_report.txt 6 reg
68 ARFGEF2 Fetal_Brain_408_AGTCAA_L001_R1_report.txt 5 reg
If you type humanSplit[[1]], it gives the data without name $Fetal_Brain_408_AGTCAA_L001_R1_report.txt
RatSplit is also essentially similar to humanSplit with difference in column order. I want to apply fisher's test to every possible pairing of replicates from humanSplit and ratSplit. Now I defined the following empty vector which I will use to store the informations of my fisher's test
humanReplicate <- vector(mode = 'character', length = 0)
ratReplicate <- vector(mode = 'character', length = 0)
pvalue <- vector(mode = 'numeric', length = 0)
For fisher's test between two replicates of humanSplit and ratSplit, I define the following function. In the function I use `geneList' which is a data.frame made by reading a file and has form:
> head(geneList)
human rat
1 5S_rRNA 5S_rRNA
2 5S_rRNA 5S_rRNA
Now here is the main function, where I use a function getGenetype which I already defined in other part of the code. Also x and y are integers :
fishertest <-function(x,y) {
ratReplicateName <- names(ratSplit[x])
humanReplicateName <- names(humanSplit[y])
## merging above two based on the one-to-one gene mapping as in geneList
## defined above.
mergedHumanData <-merge(geneList,humanSplit[[y]], by.x = "human", by.y = "humanGene")
mergedRatData <- merge(geneList, ratSplit[[x]], by.x = "rat", by.y = "ratGene")
## [here i do other manipulation with using already defined function
## getGenetype that is defined outside of this function and make things
## necessary to define following contingency table]
contingencyTable <- matrix(c(HnRn,HnRy,HyRn,HyRy), nrow = 2)
fisherTest <- fisher.test(contingencyTable)
humanReplicate <- c(humanReplicate,humanReplicateName )
ratReplicate <- c(ratReplicate,ratReplicateName )
pvalue <- c(pvalue , fisherTest$p)
}
After doing all this I do the make matrix eg to use in apply. Here I am basically trying to do something similar to double for loop and then using fisher
eg <- expand.grid(i = 1:length(ratSplit),j = 1:length(humanSplit))
junk = apply(eg, 1, fishertest(eg$i,eg$j))
Now the problem is, when I try to run, it gives the following error when it tries to use function fishertest in apply
Error in humanSplit[[y]] : recursive indexing failed at level 3
Rstudio points out problem in following line:
mergedHumanData <-merge(geneList,humanSplit[[y]], by.x = "human", by.y = "humanGene")
Ultimately, I want to do the following:
result <- data.frame(humanReplicate,ratReplicate, pvalue ,alternative, Conf.int1, Conf.int2, oddratio)
I am struggling with these questions:
In defining fishertest function, how should I pass ratSplit and humanSplit and already defined function getGenetype?
And how I should use apply here?
Any help would be much appreciated.
Up front: read ?apply. Additionally, the first three hits on google when searching for "R apply tutorial" are helpful snippets: one, two, and three.
Errors in fishertest()
The error message itself has nothing to do with apply. The reason it got as far as it did is because the arguments you provided actually resolved. Try to do eg$i by itself, and you'll see that it is returning a vector: the corresponding column in the eg data.frame. You are passing this vector as an index in the i argument. The primary reason your function erred out is because double-bracket indexing ([[) only works with singles, not vectors of length greater than 1. This is a great example of where production/deployed functions would need type-checking to ensure that each argument is a numeric of length 1; often not required for quick code but would have caught this mistake. Had it not been for the [[ limit, your function may have returned incorrect results. (I've been bitten by that many times!)
BTW: your code is also incorrect in its scoped access to pvalue, et al. If you make your function return just the numbers you need and the aggregate it outside of the function, your life will simplify. (pvalue <- c(pvalue, ...) will find pvalue assigned outside the function but will not update it as you want. You are defeating one purpose of writing this into a function. When thinking about writing this function, try to answer only this question: "how do I compare a single rat record with a single human record?" Only after that works correctly and simply without having to overwrite variables in the parent environment should you try to answer the question "how do I apply this function to all pairs and aggregate it?" Try very hard to have your function not change anything outside of its own environment.
Errors in apply()
Had your function worked properly despite these errors, you would have received the following error from apply:
apply(eg, 1, fishertest(eg$i, eg$j))
## Error in match.fun(FUN) :
## 'fishertest(eg$i, eg$j)' is not a function, character or symbol
When you call apply in this sense, it it parsing the third argument and, in this example, evaluates it. Since it is simply a call to fishertest(eg$i, eg$j) which is intended to return a data.frame row (inferred from your previous question), it resolves to such, and apply then sees something akin to:
apply(eg, 1, data.frame(...))
Now that you see that apply is being handed a data.frame and not a function.
The third argument (FUN) needs to be a function itself that takes as its first argument a vector containing the elements of the row (1) or column (2) of the matrix/data.frame. As an example, consider the following contrived example:
eg <- data.frame(aa = 1:5, bb = 11:15)
apply(eg, 1, mean)
## [1] 6 7 8 9 10
# similar to your use, will not work; this error comes from mean not getting
# any arguments, your error above is because
apply(eg, 1, mean())
## Error in mean.default() : argument "x" is missing, with no default
Realize that mean is a function itself, not the return value from a function (there is more to it, but this definition works). Because we're iterating over the rows of eg (because of the 1), the first iteration takes the first row and calls mean(c(1, 11)), which returns 6. The equivalent of your code here is mean()(c(1, 11)) will fail for a couple of reasons: (1) because mean requires an argument and is not getting, and (2) regardless, it does not return a function itself (in a "functional programming" paradigm, easy in R but uncommon for most programmers).
In the example here, mean will accept a single argument which is typically a vector of numerics. In your case, your function fishertest requires two arguments (templated by my previous answer to your question), which does not work. You have two options here:
Change your fishertest function to accept a single vector as an argument and parse the index numbers from it. Bothing of the following options do this:
fishertest <- function(v) {
x <- v[1]
y <- v[2]
ratReplicateName <- names(ratSplit[x])
## ...
}
or
fishertest <- function(x, y) {
if (missing(y)) {
y <- x[2]
x <- x[1]
}
ratReplicateName <- names(ratSplit[x])
## ...
}
The second version allows you to continue using the manual form of fishertest(1, 57) while also allowing you to do apply(eg, 1, fishertest) verbatim. Very readable, IMHO. (Better error checking and reporting can be used here, I'm just providing a MWE.)
Write an anonymous function to take the vector and split it up appropriately. This anonymous function could look something like function(ii) fishertest(ii[1], ii[2]). This is typically how it is done for functions that either do not transform as easily as in #1 above, or for functions you cannot or do not want to modify. You can either assign this intermediary function to a variable (which makes it no longer anonymous, figure that) and pass that intermediary to apply, or just pass it directly to apply, ala:
.func <- function(ii) fishertest(ii[1], ii[2])
apply(eg, 1, .func)
## equivalently
apply(eg, 1, function(ii) fishertest(ii[1], ii[2]))
There are two reasons why many people opt to name the function: (1) if the function is used multiple times, better to define once and reuse; (2) it makes the apply line easier to read than if it contained a complex multi-line function definition.
As a side note, there are some gotchas with using apply and family that, if you don't understand, will be confusing. Not the least of which is that when your function returns vectors, the matrix returned from apply will need to be transposed (with t()), after which you'll still need to rbind or otherwise aggregrate.
This is one area where using ddply may provide a more readable solution. There are several tutorials showing it off. For a quick intro, read this; for a more in depth discussion on the bigger picture in which ddply plays a part, read Hadley's Split, Apply, Combine Strategy for Data Analysis paper from JSS.

Resources