[R] Looping through names of both dataframes and column-names
Blaser Nello
nblaser at ispm.unibe.ch
Fri Apr 26 09:48:09 CEST 2013
Here are two possible ways to do it:
This would simplify your code a bit. But it changes the names of x_cs to
cs.x.
for (df in nls) {
assign(df, cbind(get(df), cs=apply(get(df), 2, cumsum)))
}
This is closer to what you have done.
for (df in nls) {
print(df)
for (var in names(get(df))) {
print(var)
assign(df, within(get(df), assign(paste0(var,"_cs"),
cumsum(get(df)[[var]]))))
}}
ls()[grep("df_",ls())]
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Daniel Egan
Sent: Donnerstag, 25. April 2013 22:19
To: r-help at r-project.org
Subject: [R] Looping through names of both dataframes and column-names
Hello all,
This seems like a pretty standard question - suppose I want to loop
through a set of similar data-frames, with similar variables, and create
new variables within them:
nl<-seq(1,5)for (i in nl) {
assign(paste0("df_",nl[i]),data.frame(x=seq(1:10),y=rnorm(10)))}
ls()[grep("df_",ls())]
nls<-ls()[grep("df_",ls())]for (df in nls) {
print(df)
for (var in names(get(df))) {
print(var)
assign(paste0(df,"$",paste0(var,"_cs")),cumsum(get(df)[[var]]))
}}
ls()[grep("df_",ls())]
The code above *almost* works, except that it creates a whole bunch of
objects of the form df_1$x_cs,df_1$yx_cs ..... What I want is 5
dataframes, with the $ elements enclosed, as usual.
Any help or guidance would be appreciated.
Much thanks,
Dan
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list