Probably be better to round the numbers first and then try to paste the %
symbol in. Also, the way you're trying to convert the second column into character
is a little... strange? I'd recommend using as.character()
for this kind of thing in the future. Based on the "--"
in that last cell, I'd assume that the Freq
column is already stored as a character.
This means to round, you will have to convert to numeric (which will give you NA
s where the "--"
values currently are), round where possible, convert to character, add the %
symbol, then replace the NA
s with "--"
again.
x <- tab[,2] #pull out this column to make it easier than typing tab[,2] everywhere
x <- as.numeric(x) #This will give you a warning about coercing to NA
x <- round(x,digits=1)
x <- paste0(x,"%") # this will also convert to character for us
x <- ifelse(x == "NA%","--",x) #Don't forget, we stuck the % on the end
tab[,2] <- x #Store back into the table
This whole process can actually be made smoother and easier to read by the use of pipes
from the {magrittr}
package.
not_empty <- tab[,2] != "--" #We only want to work on rows that aren't "--"
tab[not_empty,2] %<>% #This pipe re-assigns what's on the left
as.numeric %>% #Convert to numeric
round(digits=1) %>% #Round it
paste0("%") #Paste % on the end