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

"Dénes TÓTH" tdenes at cogpsyphy.hu
Fri Jul 29 01:36:42 CEST 2011


The problem is that you can not assign a variable to itself.

rm(list=ls())
df1 <- data.frame(ResultValue=as.character(1:5))
df2 <- data.frame(ResultValue=as.character(1:10))
frames = ls()
for (frame in frames){
     temp <- get(frame)
     temp[,"ResultValue"] = as.numeric(temp[,"ResultValue"])
     assign(frame,temp)
}

HTH,
  Denes



> 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?
>
> Thanks,
>
> Sarah
>
> 	[[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