Question

I'm working with emergency room ICD-9 code data (health diagnoses), which are three-digit codes with up to 2 decimals after (examples: 499, 499.1, 499.51, etc). Some special codes have the letter "V" instead of a first digit, such as "V10.46".

Every emergency room visit (row) can have up to 11 diagnoses codes (columns), so I used reshape() to change the dataset to long format. Now I want to use floor() to remove those decimal points. But R can't floor something with a character! I get this error: Error in Math.factor(dtl$diag) : floor not meaningful for factors

This post had some relevance but I'm wondering if there's a better way? R: Remove character observations in a variable

Any ideas?

Was it helpful?

Solution

Building off @Vincent Zoonekynd's excellent answer, If the aim was to use floor on the data, you can just strip the "V" and call floor on the rest:

x <- c("499", "499.1", "499.51", "V10.46")
# replace all occurences of "V" with nothing ("") in x:
x.stripped <- gsub("V", "", x) 
# convert to numeric so we can use floor():
x.floor <- floor(as.numeric(x.stripped))

Based off your error message, "not meaningful for factors", that column of your data has been read in as strings (because of the "V" in some of the rows), and the default behaviour of R is to convert string columns into factors (like categories).

If you get an error about gsub not working on factors, you need to convert your column to strings first:

mydf$columname <- as.character(mydf$columnname)

And then you can proceed as before.

OTHER TIPS

You can use a regular expression to remove the dot and everything after.

x <- c("499", "499.1", "499.51", "V10.46")
gsub("\\..*", "", x)
# Output:
# [1] "499" "499" "499" "V10"

For first three letters you can use substring function.

icd9 <- factor(c("499", "499.1", "499.51", "V10.46"))
substr(as.character(icd9),1,3)# as.character is used 
                              # because icd9 is factor in your data

Output

[1] "499" "499" "499" "V10"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top