我有一个数据列表,其中df中的每一列对应于来自相同长度的不同数值向量的函数值的计算。每个列表对象(Dataframe)都使用不同的函数生成。
我想把每个列表对象(dataframe)迭代到1,为每个列表对象(Dataframe)生成一个地块,列作为数据序列。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发布于 2018-01-12 23:39:19
在我看来,您的for循环很好,我不担心转换到lapply。就我个人而言,我认为当您想要做一些简单的事情时,lapply是很棒的,但是当您想要更复杂的东西时,for循环也可以同样可读的。
我唯一真正要做的改变是使用colMeans而不是apply(., 2, mean)。我还可能将trait.estimate部分和绘图部分分离开来,因为它们似乎完全不同的操作。在组织上似乎更好。
例如,提取trait.estimate计算如下所示:
# inside for loop version
trait.estimate[[i]] <- colMeans(component.estimation[[i]])
trait.estimate[[i]] <- as.data.frame(trait.estimate[[i]])
trait.estimate[[i]]$treatment <- row.names(trait.estimate[[i]])
# outside for loop lapply version
trait.estimate = lapply(component.estimation, colMeans)
trait.estimate = lapply(trait.estimate, as.data.frame)
trait.estimate = lapply(trait.estimate, function(x) x$treatment = row.names(x))
# all in one lapply version with anonymous function
trait.estimate = lapply(component.estimation, function(x) {
means = colMeans(x)
means = as.data.frame(means)
means$treatment = row.names(means)
return(means)
})哪种更好些呢?我让你来决定。想用哪种就用哪种。
https://stackoverflow.com/questions/48235223
复制相似问题