Reputation: 31
I am creating a table in R. The values in some rows should have 0 decimal places (such as number of people) while values in other rows should have 1 decimal place (e.g. percent of population).
I have the data frame, and then used the round function the round function in R to create two tables - round0 (0 decimal places) and round1 (1 decimal place).
round1<-round(prof.table[-c(2:3),], 1)
round0<-round(prof.table[2:3,], 0)
prof.table<-rbind(round0, round1)
After I combine them, I would expect that values from the round0 table would have zero decimal places, and those from round1 would have 1 decimal place. However, after rbind, values in all cells have 1 decimal place, so my integers are showing as nnn.0. How can I remove this extra decimal place from the whole numbers?
Upvotes: 1
Views: 1120
Reputation: 31
As I needed the data to present in a table, I followed @Rui 's suggestion to coerce the data into character format, and thanks to @Jonny for the tip that vectors can only be one class:
#Round certain variables to one decimal point
round1<-round(prof.table[-c(2:3),], 1)
#set as character
round1$`V1`<-as.character(round1$`V1`)
round1$`V2`<-as.character(round1$`V2`)
#Round others to zero decimal point
round0<-round(prof.table[2:3,], 0)
#set them as character
round0$`V1`<-as.character(round0$`V1`)
round0$`V2`<-as.character(round0$`V2`)
#combine into data frame
prof.table<-rbind(round0, round1)
Upvotes: 2
Reputation: 2727
You're trying to combine a numeric
value with an integer
. A vector (or data.frame column) can only have one class. Either it will force the numerics to be integers, or the integers to be numeric. Given this choice, the latter is preferable, as there is no data loss from converting 2
to 2.0000
.
This will help to explain the differences in classes: What's the difference between integer class and numeric class in R
An example:
# create an integer vector x (0 decimal places) & numeric vector y (>0 decimal places)
x <- as.integer(1:3)
y <- runif(3)
# check their classes to confirm
class(x)
class(y)
# bind them together, and view class
z <- c(x, y)
z
class(z)
Upvotes: 2