[R] Rounding variables in a data frame

Pete B Peter.Brecknock at bp.com
Sat Jan 15 05:53:19 CET 2011


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.



More information about the R-help mailing list