Skip to content
Prev 247373 / 398503 Next

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