I have a dataframe, and I wish to round all of the numbers (ready for export). This must be straightforward, but I am having problems because some bits of the dataframe are not numeric numbers. For example I want to round the figures to the nearest whole number in the example below:
ID = c("a","b","c","d","e")
Value1 = c("3.4","6.4","8.7","1.1","0.1")
Value2 = c("8.2","1.7","6.4","1.9","10.3")
df<-data.frame(ID,Value1,Value2)
Can anyone help me out? I can round individual columns (e.g., round(df$Value1, 2)
) but I want to round a whole table which contains some columns which are not numeric.
First make sure your number columns are numeric:
ID = c("a","b","c","d","e")
Value1 = as.numeric(c("3.4","6.4","8.7","1.1","0.1"))
Value2 = as.numeric(c("8.2","1.7","6.4","1.9","10.3"))
df<-data.frame(ID,Value1,Value2, stringsAsFactors = FALSE)
Then, round only the numeric columns:
df[,-1] <-round(df[,-1],0) #the "-1" excludes column 1
df
ID Value1 Value2
1 a 3 8
2 b 6 2
3 c 9 6
4 d 1 2
5 e 0 10