简体   繁体   English

将某些功能应用于多个对象

[英]Applying some functions to multiple objects

I am on Mac OS 10.10 with R 3.1.1 我在Mac OS 10.10和R 3.1.1上

Suppose I have the following data frames a and b with the same attributes: 假设我具有以下具有相同属性的数据帧ab

a<- structure(list(X1 = 1:5, X2 = 6:10), .Names = c("X1", "X2"), row.names = c(NA, 
-5L), class = "data.frame")
b<- structure(list(X1 = 11:15, X2 = 16:20), .Names = c("X1", "X2"
), row.names = c(NA, -5L), class = "data.frame")

and suppose I need to do some cleaning/apply some functions (like dropping column and multiply the first column by 2) on both a and b at the same time such that the original data frames reflect the changes with the following desired output: 并假设我需要同时在ab上执行一些清理/应用某些功能(例如删除列并将第一列乘以2),以便原始数据帧反映具有以下所需输出的更改:

> a
  X1 
1  2 
2  4 
3  6 
4  8
5 10

> b
  X1
1 22
2 24
3 26
4 28
5 30

I have just learnt the for loops and *apply functions but get confused when applying them on the data frames I have (which are not a and b but much bigger). 我刚刚学习了for循环和* apply函数,但是在将它们应用于我拥有的数据帧(不是ab而是更大)时感到困惑。

It is generally encouraged (by the R Core team memebers) that if you have several data sets that you want to simultaneously operate on, you should keep them all in a list. 通常,(由R Core团队成员鼓励)如果要同时处理多个数据集,则应将它们全部保留在列表中。 In order to achieve your goal, you can simply use mget and ls to retreive them from the global environment and then simply replace with first column multiplied by 2, eg, 为了实现您的目标,您可以简单地使用mgetls从全局环境中删除它们,然后简单地替换为第一列乘以2,例如,

lapply(mget(ls(pattern = "[a-z]")), function(x) x <- x[1] * 2)
# $a
# X1
# 1  2
# 2  4
# 3  6
# 4  8
# 5 10
# 
# $b
# X1
# 1 22
# 2 24
# 3 26
# 4 28
# 5 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM