Home > Net >  Rollup column values to 0 or 1 digits in R
Rollup column values to 0 or 1 digits in R

Time:02-05

I have a table with 3 columns and 27,000 observations. I want to rollup the phecodes to one digit or 0 digits if no one digit phecode is available. How can I do this in R? I have an example of what I want to do below.

Part of a table

ICD     Flag Phecode
008.45  9    008
008.45  9    008.5
008.45  9    008.52
008.46  9    008
008.46  9    008.5
008.47  9    008
008.47  9    008.5

Desired output

ICD    Flag Phecode
008.45  9   008
008.45  9   008
008.45  9   008.5
008.46  9   008
008.46  9   008
008.47  9   008
008.47  9   008

Thanks in advance!

CodePudding user response:

It looks like you want to

  1. round Phecode to tenths if two digits after decimals, otherwise truncate to whole number
  2. maintain leading zeros
# Sample data
Phecode <- c(008, 008.5, 008.52)
# nchar will read number with no decimal and leading zeros as "1", with decimal and tenth digit only as 3. If two numerals after decimal will be nchar >3 and round to tenth. Paste0 will add leading zeros.
paste0("00", ifelse(nchar(Phecode) > 3, round(Phecode, 1), round(Phecode,0)))

Gives:

"008"   "008"   "008.5"

You can coerce to numeric or add to df as df$Phecode <- Phecode

  •  Tags:  
  • Related