循环通过数据框和变量名 [英] Loop through data frame and variable names

查看:125
本文介绍了循环通过数据框和变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用FOR循环自动化R中的一些图表的方法:

I am looking for a way to automate some diagrams in R using a FOR loop:

dflist <- c("dataframe1", "dataframe2", "dataframe3", "dataframe4")

for (i in dflist) {
  plot(i$var1, i$var2)
}

所有数据帧都有相同的变量,即var1,var2。

All dataframes have the same variables, i.e. var1, var2.

似乎 for 循环不是这里最优雅的解决方案,但我不明白如何使用

It seems for loops are not the most elegant solution here, but I don't understand how to use the apply functions for diagrams.

编辑:

我的原始示例使用 mean()在原始问题中没有帮助,所以我将其更改为绘图函数。

My original example using mean() didn't help in the original question, so I changed it to a plot function.

推荐答案

为了进一步添加Beasterfield的答案,似乎你想对每个数据框架进行一些复杂的操作。

To further add to Beasterfield's answer, it seems like you want to do some number of complex operations on each of the data frames.

可以在apply语句中具有复杂的函数。所以你现在有:

It is possible to have complex functions within an apply statement. So where you now have:

for (i in dflist) {
  # Do some complex things
}

这可以翻译成:

lapply(dflist, function(df) {
  # Do some complex operations on each data frame, df
  # More steps

  # Make sure the last thing is NULL. The last statement within the function will be
  # returned to lapply, which will try to combine these as a list across all data frames.
  # You don't actually care about this, you just want to run the function.
  NULL
})

使用情节的一个更具体的例子:

A more concrete example using plot:

# Assuming we have a data frame with our points on the x, and y axes,
lapply(dflist, function(df) {
  x2 <- df$x^2
  log_y <- log(df$y)
  plot(x,y)
  NULL
})

您还可以编写多个参数的复杂函数:

You can also write complex functions which take multiple arguments:

lapply(dflist, function(df, arg1, arg2) {
  # Do something on each data.frame, df
  # arg1 == 1, arg2 == 2 (see next line)
}, 1, 2) # extra arguments are passed in here

希望这可以帮助你!

这篇关于循环通过数据框和变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆