【发布时间】:2018-06-22 10:40:45
【问题描述】:
我有一个数据框列表,其中 df 中的每一列对应于对来自相同长度的不同数字向量的函数值的评估。 每个列表对象(数据框)都是用不同的函数生成的
我想遍历每个列表对象(数据框)以 1. 为每个列表对象(数据框)生成一个图,以列作为数据系列。 2. 生成新数据框的新列表,其中包含原始数据框的每一列均值的列
下面的代码是功能性的,但是有没有更好的方法来使用 apply 语句并避免 for 循环?
plots <- list()
trait.estimate <- list()
for(i in 1:length(component.estimation)) { #outter loop start
component.estimation[[i]]$hr <- hr #add hr vector to end of dataframe
temporary.df <- melt(component.estimation[[i]] , id.vars = 'hr', variable.name = 'treatment')
#Store a plot of each df
plots[[i]] <- ggplot(temporary.df, aes(hr , value), group = treatment, colour = treatment, fill = treatment) +
geom_point(aes(colour = treatment, fill = treatment))+
geom_line(aes(colour= treatment, linetype = treatment))+
ggtitle( names(component.estimation)[i])+ #title to correspond to trait
theme_classic()
#Generate column averages for each df
trait.estimate[[i]] <- apply(component.estimation[[i]] ,2, mean)
trait.estimate[[i]] <- as.data.frame(trait.estimate[[i]])
trait.estimate[[i]]$treatment <- row.names(trait.estimate[[i]])
} #outter loop close
【问题讨论】:
-
请提供样本数据
-
您的
for循环对我来说看起来不错,我不会担心转换到lapply。就我个人而言,我认为lapply非常适合当你想做一些简单的事情,但当你想做一些更复杂的事情时,(或一次做多项事情)for循环是有意义的。
标签: r list dataframe ggplot2 apply