首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用apply语句而不是for循环来执行这段代码?

如何使用apply语句而不是for循环来执行这段代码?
EN

Stack Overflow用户
提问于 2018-01-12 23:05:02
回答 1查看 49关注 0票数 0

我有一个数据列表,其中df中的每一列对应于来自相同长度的不同数值向量的函数值的计算。每个列表对象(Dataframe)都使用不同的函数生成。

我想把每个列表对象(dataframe)迭代到1,为每个列表对象(Dataframe)生成一个地块,列作为数据序列。2.生成一个新的数据格式列表,该列表包含来自原始数据的每一列平均值的一列。

下面的代码是功能性的,但是是否有更好的方法来使用apply语句并避免for循环?

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-12 23:39:19

在我看来,您的for循环很好,我不担心转换到lapply。就我个人而言,我认为当您想要做一些简单的事情时,lapply是很棒的,但是当您想要更复杂的东西时,for循环也可以同样可读的。

我唯一真正要做的改变是使用colMeans而不是apply(., 2, mean)。我还可能将trait.estimate部分和绘图部分分离开来,因为它们似乎完全不同的操作。在组织上似乎更好。

例如,提取trait.estimate计算如下所示:

代码语言:javascript
运行
复制
# 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)
})

哪种更好些呢?我让你来决定。想用哪种就用哪种。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48235223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档