[R] How to assign names to global data frames created in a function
arun
smartpink111 at yahoo.com
Wed Sep 4 00:12:36 CEST 2013
Hi,
May be this helps you in getting started.
set.seed(29)
df1<- as.data.frame(matrix(sample(1:20,5*10,replace=TRUE),5,10))
cond<- c("V1eq2","V8eq2","V6eq4orV8eq7")
fun1<- function(df,prefix,cond){
lst1<- list(df[df$V1==2,],df[df$V8==2,],df[df$V6==4|df$V8==7,])
for(i in seq_along(cond)){
assign(paste(prefix,cond[i],sep="_"),lst1[[i]],envir=.GlobalEnv)
print(paste(prefix,cond[i],sep="_"))}
}
fun1(df1,"frame1",cond)
#[1] "frame1_V1eq2"
#[1] "frame1_V8eq2"
#[1] "frame1_V6eq4orV8eq7"
frame1_V1eq2
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#1 2 2 20 17 14 8 8 2 13 18
frame1_V8eq2
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#1 2 2 20 17 14 8 8 2 13 18
#5 12 5 4 8 13 4 10 2 2 13
frame1_V6eq4orV8eq7
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#3 3 18 7 8 20 18 2 7 20 15
#4 7 3 13 18 20 14 15 7 14 12
#5 12 5 4 8 13 4 10 2 2 13
A.K.
----- Original Message -----
From: Matt Strauser <syntereo at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Tuesday, September 3, 2013 10:19 AM
Subject: [R] How to assign names to global data frames created in a function
I have several data frames containing similar data. I'd like to pass these
data frames to a function for processing. The function would create newly
named "global" data frames containing the processed data. I cannot figure
out how to assign names to the data frames in Step 1 or Step 2 in the
following example:
# sample function in pseudo code
processdf <- function(df, prefix) {
# df - data frame containing data for processing
# prefix - string to become the first part of the names of the resulting
data frames
# Step 1 - processs df into several subsets
df1 <<- subset(df, df$cond1 & df$cond2 & ...)
df2 <<- subset(df, df$cond3 & df$cond4 & ...)
df3 <<- subset(df, df$cond5 & df$cond6 & ...)
# and so on....for many more steps with resulting data frames
# Step 2 - rename the resulting global data frames
rename "df1" to prefix + "cond1cond2"
rename "df2" to prefix + "cond3cond4"
rename "df3" to prefix + "cond5cond6"
# and so on for the remaining data frames
}
Example using data frames: frame1 and frame2:
processdf(frame1, "frame1")
# produces these data frames:
frame1cond1cond2
frame1cond3cond4
frame1cond5cond6
processdf(frame2, "frame2")
# produces these data frames:
frame2cond1cond2
frame2cond3cond4
frame2cond5cond6
Thank you for your thoughts,
Matt
[[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