R 中多个数据帧的相同功能 [英] Same function over multiple data frames in R

查看:27
本文介绍了R 中多个数据帧的相同功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 新手,这是一个非常简单的问题.我发现了很多与我想要的相似的东西,但不完全是.基本上我有多个数据框,我只想在所有这些数据框上运行相同的功能.for 循环可以工作,但我不确定如何正确设置它以调用数据帧.它似乎也最喜欢 R 的 lapply 方法.我也玩过 get 函数,但无济于事.如果这是一个重复的问题,我深表歉意.任何帮助将不胜感激!

I am new to R, and this is a very simple question. I've found a lot of similar things to what I want but not exactly it. Basically I have multiple data frames and I simply want to run the same function across all of them. A for-loop could work but I'm not sure how to set it up properly to call data frames. It also seems most prefer the lapply approach with R. I've played with the get function as well to no avail. I apologize if this is a duplicated question. Any help would be greatly appreciated!

这是我过于简化的示例:2个数据框:df1,df2

Here's my over simplified example: 2 data frames: df1, df2

df1
start stop ID
0     10   x
10    20   y
20    30   z

df2
start stop ID
0     10   a
10    20   b
20    30   c

我想要的是第 4 列,其中包含两个 dfs 的开始和停止的平均值

what I want is a 4th column with the average of start and stop for both dfs

df1
start stop ID  Avg
0     10   x    5 
10    20   y    15
20    30   z    25

我可以一次完成一个数据框:

I can do this one data frame at a time with:

df1$Avg <- rowMeans(subset(df1, select = c(start, stop)), na.rm = TRUE)

但我想在所有数据帧上运行它.

but I want to run it on all of the dataframes.

推荐答案

制作一个数据框列表,然后使用 lapply 将函数应用于它们.

Make a list of data frames then use lapply to apply the function to them all.

df.list <- list(df1,df2,...)
res <- lapply(df.list, function(x) rowMeans(subset(x, select = c(start, stop)), na.rm = TRUE))
# to keep the original data.frame also
res <- lapply(df.list, function(x) cbind(x,"rowmean"=rowMeans(subset(x, select = c(start, stop)), na.rm = TRUE)))

然后 lapply 将按顺序输入每个数据帧作为 x.

The lapply will then feed in each data frame as x sequentially.

这篇关于R 中多个数据帧的相同功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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