user1038577
user1038577

Reputation: 21

convert height as string X'X" to numeric

I have a column of heights formatted as X'X" (feet and inches) and need help converting it to inches. For example, 6'2" would be 74 (inches).

Using dput(), this is the list:

h <- structure(c(3L, 2L, 5L, 1L, 4L), .Label = c("4'8\"", "5'1.5\"", 
               "5'10.5\"", "5'2.5\"", "5'6\""), class = "factor")

Upvotes: 2

Views: 2399

Answers (1)

joran
joran

Reputation: 173677

You have a factor. You can convert it to a character vector, split on the foot and inch symbols, and then use sapply to do the conversion in an anonymous function:

h <- structure(c(3L, 2L, 5L, 1L, 4L), .Label = c("4'8\"", "5'1.5\"", 
                "5'10.5\"", "5'2.5\"", "5'6\""), class = "factor")

sapply(strsplit(as.character(h),"'|\""),
        function(x){12*as.numeric(x[1]) + as.numeric(x[2])})

[1] 70.5 61.5 66.0 56.0 62.5

Upvotes: 8

Related Questions