[R] Rounding variables in a data frame

Bill.Venables at csiro.au Bill.Venables at csiro.au
Sat Jan 15 06:07:14 CET 2011


If you can specify the omitted columns as numbers there is a quick way to do it.  e.g.

> d
          d1       d2        d3        d4
1   9.586524 4.833417 0.8142588 -3.237877
2  11.481521 6.536360 2.3361894 -4.042314
3  10.243192 5.506440 2.0443788 -3.478543
4   9.969548 6.159666 3.0449121 -4.827746
5   9.193832 4.085796 3.0176759 -2.199658
6  10.821571 5.442870 1.2630331 -3.483939
7   9.288714 5.756906 1.2432079 -4.387761
8   8.258251 7.729755 0.9170335 -5.416554
9  10.371080 6.234921 2.4462774 -4.433582
10  9.378106 5.389561 4.0592613 -3.433946
> out <- d
> out[-3] <- round(d[-3])
> out
   d1 d2        d3 d4
1  10  5 0.8142588 -3
2  11  7 2.3361894 -4
3  10  6 2.0443788 -3
4  10  6 3.0449121 -5
5   9  4 3.0176759 -2
6  11  5 1.2630331 -3
7   9  6 1.2432079 -4
8   8  8 0.9170335 -5
9  10  6 2.4462774 -4
10  9  5 4.0592613 -3
> 

If you want to specify the column names as a character vector, this is almost as easy.  e.g.

> omit <- c("d1", "d3")
> leave <- match(omit, names(d))
> out <- d
> out[-leave] <- round(d[-leave])
> out
          d1 d2        d3 d4
1   9.586524  5 0.8142588 -3
2  11.481521  7 2.3361894 -4
3  10.243192  6 2.0443788 -3
4   9.969548  6 3.0449121 -5
5   9.193832  4 3.0176759 -2
6  10.821571  5 1.2630331 -3
7   9.288714  6 1.2432079 -4
8   8.258251  8 0.9170335 -5
9  10.371080  6 2.4462774 -4
10  9.378106  5 4.0592613 -3
> 

Bill Venables
________________________________________
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of Pete B [Peter.Brecknock at bp.com]
Sent: 15 January 2011 14:53
To: r-help at r-project.org
Subject: [R] Rounding variables in a data frame

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.



More information about the R-help mailing list