Reputation: 593
I have a list of dataframes in Rlist
as such:
Rlist = lapply(1:5,function(i){
data.frame(Frame_times = seq(0,1,length.out=100),L1=runif(100), L2 = runif(100), L3 = runif(100))
})
names(Rlist) = letters[1:5]
As you can see, there is a list containing 5 dataframes. Within each dataframe, there are three columns called L1
, L2
, and L3
. I want to use these three columns from each dataframe to create plots (specifically, spectral analysis plots), and I want to do this systematically using loops.
The ineffective code below tries to do the following: Creates plots using the three columns of interest inside each dataframe in Rlist
, and puts them in a new list called aplotfinal
. In the end, I should have a list of lists that contain plots called aplotfinal
, with 15 plots in total, but more specifically, 5 lists with 3 plots per list.
aplotfinal <- lapply(1:length(Rlist),function(i){
a <- Rlist[[i]][,-1]
for(t in colnames(a)){
del <- 0.016667
x.spec <- spectrum(a$t, log = "no", plot = FALSE)
spx <- x.spec$freq/del
spy <- 2*x.spec$spec
aplotfinal[[i]] <- qplot(y = spy,x=spx,geom="line") +
ggtitle(names(Rlist)[i]) +
xlab("frequency")+ylab("spectral density")
}
})
Hope this makes sense. Thank you!
Upvotes: 1
Views: 61
Reputation: 76450
The following code is the question's code corrected. It outputs a list with 5 members, each a list with 3 plots.
aplotfinal <- lapply(1:length(Rlist),function(i){
a <- Rlist[[i]][,-1]
lapply(colnames(a), function(t){
del <- 0.016667
x.spec <- spectrum(a[[t]], log = "no", plot = FALSE)
spx <- x.spec$freq/del
spy <- 2*x.spec$spec
qplot(y = spy,x=spx,geom="line") +
ggtitle(names(Rlist)[i]) +
xlab("frequency")+ylab("spectral density")
})
})
To see the first plot of the first sub-list:
aplotfinal[[1]][[1]]
Upvotes: 2