How to use different parameters based on a vector for each iteration of lapply?

StackOverflow https://stackoverflow.com/questions/22945476

  •  30-06-2023
  •  | 
  •  

Question

I have a list of vectors for which I am lapplying the function lines to plot the content of each of the elements in the list. Example code following:

l <- list()
for(i in 1:10){l[[i]] <- rnorm(10)}
plot(l[[1]], t='n')
lapply(l, lines)

Is there a way of telling lapply that for each element use a different parameter, for instance, color or line type, so I can easily attribute the corresponding features I want to each element of the list? For instance, I'd like to have a vector of colors that match a particular element on the list.

Was it helpful?

Solution 2

I found that mapply is the way to go

OTHER TIPS

I came up with the same lapply approach as jlhoward. Here's an example which colors the line based on whether the average is greater than zero or not:

lapply(l, function(line) {lines(line, col=ifelse(mean(line) > 0, 'red', 'blue'))})

That said, your example uses a loop to create the sample data. If your actual code is using a loop, why not plot each line as part of the data-generating loop? That way you can calculate whatever plotting parameters you need on a per-line basis. Normally, I wouldn't advocate a loop over an apply function -- R is really slow at loops! But unless you are plotting tens of thousands of lines, you probably won't notice much of a performance hit. (Also, bear in mind that the lapply approach is going to return a NULL value for each line plotted ... which is kinda awkward.)

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