[R] Looping through data sets to change column from character to numeric

Greg Snow Greg.Snow at imail.org
Sun Jul 31 04:22:00 CEST 2011

Others have shown how to do this, but a better approach may be to load your .Rdata file into a new environment rather than the global environment, then you can work with the environment (and all the objects in it) using lapply, or loops with [[]] instead of fighting with get and assign.

Something like:

> mydfs <- new.env()
> load( '.Rdata', env=mydfs
> mydfs <- lapply( mydfs, function(x) { x$ResultValue <- as.numeric(x$ResultValue); x} )


> mydfs <- lapply( mydfs, function(x) within(x, ResultValue <- as.numeric(ResultValue) ) )


> for( frame in ls(env=mydfs) ) {
+  mydfs[[frame]]$ResultValue <- as.numeric( mydfs[[frame]]$ResultValue )
+ }

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Sarah Henderson
Sent: Thursday, July 28, 2011 5:09 PM
To: R List
Subject: [R] Looping through data sets to change column from character to numeric

Greetings to all --

I am having a silly problem that I just can't solve.  Someone has given me
an .RData file will hundreds of data frames.  Each data frame has a column
named ResultValue, currently character when it should be numeric.  I want to
loop through all of the data frames to change the variable to numeric, but I
cannot figure out how to do it. My best guess was along the lines of:

frames = ls()
for (frame in frames){
     assign(frame, get(frame), .GlobalEnv)
     frame[,"ResultValue"] = as.numeric(frame[,"ResultValue"])

It doesn't work.  After the assign() the frame object remains the character
name of the dataframe I am trying to change.  If I do the following, the
TEST object comes out just fine.

frames = ls()
for (frame in frames){
     assign("TEST", get(frame), .GlobalEnv)
     TEST[,"ResultValue"] = as.numeric(TEST[,"ResultValue"])

Seems like it should be simple, but I am misunderstanding something and not
following the logic.  Any insight?



	[[alternative HTML version deleted]]

R-help at r-project.org mailing list
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