Applying some functions to multiple objects

拈花ヽ惹草 提交于 2020-11-28 02:09:29

问题


I am on Mac OS 10.10 with R 3.1.1

Suppose I have the following data frames a and b with the same attributes:

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:

> 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).


回答1:


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. 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, e.g.,

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


来源:https://stackoverflow.com/questions/28023427/applying-some-functions-to-multiple-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!