adding special character with summary

Do we have any solution for a case below
I have a calculated summary like below

Cat Freq N
CA 22.12345 14
IT 55.34532 14
MC -- 14

class(tab[,2])= character
now i want to add "%" and round values to one digit

tab[,2]<-ifelse(tab[,2]=="--","--", paste0(round(tab[,2],digits = 1),"%"))

but getting error
Error in round(tab[, 2], digits = ) :
non-numeric argument to mathematical function

seems like you transitioned from numeric to character too early in your workflow.
It probably makes sense to rethink your prior code, but if you are unable (for some reason) you could try parsing the character as numerics with readr packages helper functions,


but I think that would be less than optimal.

tab[,2] <- readr::parse_number(tab[,2])
this converting my summary from "--" to NA

Cat Freq N
CA 22.12345 14
IT 55.34532 14
MC NA 14

sure. thats as expected.
so at the same time you will need to transform numbers to formatted strings with percent signs on them, you'll be wanting to convertn NA's to -- or whatever else. but there is a strong implication that if you went back youd end up with a more elegant solution than one which goes numeric -> char -> numeric char.
having a workflow of numeric -> char has obvious benefits.

actually I am not getting properly, Can you explain more with my code, also please explain readr::parse_number("5.55") is doing

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 NAs where the "--" values currently are), round where possible, convert to character, add the % symbol, then replace the NAs 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

Thanks alot, so by your guidance, i have done round before ...and it works
thanks again.....keep this social guidance
more power to you

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.