[R] a question about replacing the value in the data.frame

Joshua Wiley jwiley.psych at gmail.com
Thu Sep 9 00:21:04 CEST 2010


Hello Karena,

dat <- as.data.frame(matrix(sample(0:2, 4000000, replace = TRUE), ncol = 4000))

# if it is a data frame and has to stay that way
# the option that comes to mind is apply()
apply(dat, 2, function(x) {ifelse(x==2, 1, x)})

# if it can be or can be converted to a matrix
dat2 <- as.matrix(dat)
dat2[dat2 == 2] <- 1


On my system, the times for each method were:

> system.time(apply(dat, 2, function(x) {ifelse(x==2, 1, x)}))
   user  system elapsed
  5.472   0.296   6.803
> system.time(dat2[dat2 == 2] <- 1)
   user  system elapsed
  0.584   0.136   0.763

Hope that helps,

Josh

On Wed, Sep 8, 2010 at 1:48 PM, karena <dr.jzhou at gmail.com> wrote:
>
> I have a data.frame as follows:
> v1     v2     v3     v4     v5.....v100
> 1       1       0       0      1        2
> 2       1       2       1      0        1
> 1       1       1       2      1        0
> .        .        .       .       .        .
> .        .        .       .       .        .
> 1       2       2       1       1       0
>
> so for this data set, what I wanna do is to replace all the '2' with '1',
> how can I do it in an efficient way?
>
> thank you,
>
> karena
> --
> View this message in context: http://r.789695.n4.nabble.com/a-question-about-replacing-the-value-in-the-data-frame-tp2532010p2532010.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list