[R] Rounding variables in a data frame

Phil Spector spector at stat.berkeley.edu
Sat Jan 15 08:16:29 CET 2011


Is sapply really necessary here?

> exc = !names(d) %in% "d3"
> d[,exc] = round(d[,exc])
> d
    d1 d2         d3 d4
1  10  6  2.3749642 -4
2  11  6 -0.2081097 -2
3  10  4  1.2675955 -4
4  10  8  1.2468859 -2
5  10  6  2.7193027 -4
6   9  6  1.9195531 -5
7   9  6  2.8188036 -6
8  10  7  2.5755148 -4
9  11  5  2.4037376 -6
10 11  5  3.4295063 -5

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu

On Fri, 14 Jan 2011, Joshua Wiley wrote:

> 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/
>
> ______________________________________________
> 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