[R] Rounding variables in a data frame

Joshua Wiley jwiley.psych at gmail.com
Sat Jan 15 06:28:42 CET 2011


Hi Pete,

Here is one option.  The first part of sapply() just serves to get all
names of d except those you excluded in 'exc'.  If you were including
fewer variables than you were excluding, just get rid of the logical !
operator.

d <- data.frame(d1 = rnorm(10, 10), d2 = rnorm(10, 6),
  d3 = rnorm(10, 2), d4 = rnorm(10, -4))

exc <- "d3"

cbind(d[, exc, drop = FALSE],
  sapply(names(d)[!names(d) %in% exc], function(x) round(d[, x])))


HTH,

Josh

On Fri, Jan 14, 2011 at 8:53 PM, Pete B <Peter.Brecknock at bp.com> wrote:
>
> Hi All
>
> I am trying to use the round function on some columns of a dataframe while
> leaving others unchanged. I wish to specify those columns to leave
> unchanged.
>
> My attempt is below - here, I would like the column d3 to be left but
> columns d1, d2 and d4 to be rounded to 0 decimal places. I would welcome any
> suggestions for a nicer way of doing this.
>
> d1= rnorm(10,10)
> d2= rnorm(10,6)
> d3= rnorm(10,2)
> d4= rnorm(10,-4)
>
> d = data.frame(d1,d2,d3,d4)
>
> x= NULL
> for (i in 1:ncol(d)){
>  if (colnames(d)[i] =="d3"){x[i] = d[i]
>  } else { x[i] = round(d[i])}
>  out = do.call(cbind,x)
> }
>
> colnames(out) = colnames(d)
>
> Thanks and regards
>
> Pete
> --
> View this message in context: http://r.789695.n4.nabble.com/Rounding-variables-in-a-data-frame-tp3218729p3218729.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