[R] How to assign names to global data frames created in a function

David Winsemius dwinsemius at comcast.net
Tue Sep 3 22:09:13 CEST 2013


On Sep 3, 2013, at 7:19 AM, Matt Strauser wrote:

> 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

Generally subset does not need to have 'df$cond1' used. It uses nonstandard evaluation and will assume that unquoted tokens are column names, so this can be wrtten:

>  df1 <- subset(df, cond1 & cond2 )
>  df2 <- subset(df, cond3 & cond4)
>  df3 <- subset(df, cond5 & cond6 )

There is, however, this warning in the help file: "For programming it is better to use the standard subsetting functions like `[`, and in particular the non-standard evaluation of argument subset can have unanticipated consequences." A similar warning is seen on the help page for 'with'. So this would be advised

df1 <- df[ df[, 'cond1'] & df[,'cond2'], ]

> 
> # Step 2 - rename the resulting global data frames
>   rename "df1" to prefix + "cond1cond2"

?assign  # e.g.:
# untested in absence of reproducible example
# You should learn to use dput()

assign(paste0(prefix, "cond1", "cond2"), df1, envir=.GlobalEnv)

And please read the manual of your chosen mail-client and learn to post to Rhelp in plain text.

-- David

>   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]]

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list