循环遍历数据框和变量名称

Tim*_* S. 6 variables loops r dataframe

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

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

for (i in dflist) {
  plot(i$var1, i$var2)
}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:

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

Sco*_*hie 12

为了进一步添加Beasterfield的答案,您似乎希望在每个数据帧上执行一些复杂的操作.

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

for (i in dflist) {
  # Do some complex things
}
Run Code Online (Sandbox Code Playgroud)

这可以翻译为:

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
})
Run Code Online (Sandbox Code Playgroud)

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

# 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
})
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助你!


Bea*_*eld 6

关于您的实际问题,您应该学习如何访问data.frames,matrixs或lists的单元格,行和列.从你的代码我想你想要访问jdata.frame的第列i,所以它应该读取:

mean( i[,j] )
# or
mean( i[[ j ]] )
Run Code Online (Sandbox Code Playgroud)

$操作员可以,如果你想在你的data.frame访问特定变量的前提下使用,例如i$var1.此外,它的性能低于[, ]或通过访问[[]].

然而,尽管没有错,但for循环的使用并不是很好.您应该阅读有关矢量化函数和apply族的信息.因此,您的代码可以轻松地重写为:

set.seed(42)
dflist <- vector( "list", 5 )
for( i in 1:5 ){
  dflist[[i]] <- data.frame( A = rnorm(100), B = rnorm(100), C = rnorm(100) )
}
varlist <- c("A", "B")

lapply( dflist, function(x){ colMeans(x[varlist]) } )
Run Code Online (Sandbox Code Playgroud)