Using lapply with changing arguments
Apply over list names rather than list elements. E.g.:
somelist <- list('USA'=rnorm(10), 'Europe'=rnorm(10), 'Switzerland'=rnorm(10))
anotherlist <- list('USA'=5, 'Europe'=10, 'Switzerland'=4)
lapply(names(somelist), function(i) somelist[[i]] / anotherlist[[i]])
EDIT:
You also ask if there is a way "except for a loop" to do this "efficiently". You should note that the apply will not necessarily be more efficient. Efficiency will probably be determined by how quick your inner function is. If you want to operate on each elements of a list, you will need a loop, whether it is hidden in an apply() call or not. Check this question: Is R's apply family more than syntactic sugar?
The example I gave above can be re-written as a for loop, and you can make some naive benchmarks:
fun1 <- function(){
lapply(names(somelist), function(i) somelist[[i]] / anotherlist[[i]])
}
fun2 <- function(){
for (i in names(somelist)){
somelist[[i]] <- somelist[[i]] / anotherlist[[i]]
}
return(somelist)
}
library(rbenchmark)
benchmark(fun1(), fun2(),
columns=c("test", "replications",
"elapsed", "relative"),
order="relative", replications=10000)
The output of the benchmark on my machine was this:
test replications elapsed relative
1 fun1() 10000 0.145 1.000000
2 fun2() 10000 0.148 1.020690
Although this is not a real work application and the functions are not realistic tasks, you can see that the difference in computation time is quite negligible.
passing several arguments to FUN of lapply (and others *apply)
If you look up the help page, one of the arguments to lapply
is the mysterious ...
. When we look at the Arguments section of the help page, we find the following line:
...: optional arguments to ‘FUN’.
So all you have to do is include your other argument in the lapply
call as an argument, like so:
lapply(input, myfun, arg1=6)
and lapply
, recognizing that arg1
is not an argument it knows what to do with, will automatically pass it on to myfun
. All the other apply
functions can do the same thing.
An addendum: You can use ...
when you're writing your own functions, too. For example, say you write a function that calls plot
at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ...
(as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot
.
R lapply with several dynamic arguments
Your result from mapply() is because the function tries to convert the output to a matrix with the simplify argument by default. You can get your desired output with the following:
prices <- mapply(lots$ticker, FUN = tq_get,
from = lots$buy_date,
get = "stock.prices",
to = today(), SIMPLIFY = FALSE)
Applying a function with two arguments using Lapply
Change your function to
testFunc<-function(x,y){
return(c(length(x), nrow(y)))
}
By default, a R function returns the last evaluated value
Apply Function Using Multiple Changing Arguments in R
No need for apply
:
#define function
myfunc <- function(var1, var2, var3){
result <- var1*var2*var3
return(result)
}
#dummy data
dat <- data.frame(A=c(1,2,3),B=c(4,5,6),C=c(7,8,9))
#test function
myfunc(dat$A,dat$B,dat$C)
#output
[1] 28 80 162
Generate html code using lapply() with multiple arguments
You can use apply
row-wise, and specify class, id, and content from your data frame as follows.
library(htmltools)
tags$div(apply(df, 1, function(x) {
tags$p(class = x[["class"]], id = x[["id"]], x[["paragraph"]])
}))
Output
<div>
<p class="alert" id="id_1">paragraph1</p>
<p class="good" id="id_2">paragraph2</p>
<p class="alert" id="id_3">paragraph3</p>
</div>
Related Topics
Multiple Boxplots Using Ggplot
Installing R 3.5.0 with --Enable-R-Shlib
How to Do Conditional Grouping of Data in R
R: How to Draw a Line with Multiple Arrows in It
How to Run Lm Regression for Every Column in R
How to Make a Matrix from a List of Vectors in R
Here We Go Again: Append an Element to a List in R
Reorder Rows Using Custom Order
What Is a Good Way to Read Line-By-Line in R
Can't Change Fonts in Ggplot/Geom_Text
Replace Na with Groups Mean in a Non Specified Number of Columns
Loop Character Values in Ggtitle
R How to Convert a Numeric into Factor with Predefined Labels
Create Unique Identifier from the Interchangeable Combination of Two Variables
Link Selectinput with Sliderinput in Shiny