R - Converting Fractions in Text to Numeric

前端 未结 2 905
一整个雨季
一整个雨季 2021-02-20 11:23

I\'m trying to convert, for example, \'9¼\"\'to \'9.25\' but cannot seem to read the fraction correctly.

Here\'s the data I\'m working with:

library(XM         


        
2条回答
  •  别那么骄傲
    2021-02-20 11:51

    I don't think this is clever or efficient compared to alternatives, but this uses gsub to replace the " symbol and convert each fraction to its decimal, before converting to numeric:

    #data (I've not downloaded XML for this, so maybe the encoding will make a difference?)
    combine = data.frame(Hands = c('1"','1⅛"','1¼"','1⅜"','1½"','1⅝"','1¾"','1⅞"'))
    
    #remove the "
    combine$Hands = gsub('"', '', combine$Hands)
    
    #replace each fraction with its decimal form
    combine$Hands = gsub("⅛", ".125", combine$Hands)
    combine$Hands = gsub("¼", ".25", combine$Hands)
    combine$Hands = gsub("⅜", ".375", combine$Hands)
    combine$Hands = gsub("½", ".5", combine$Hands)
    combine$Hands = gsub("⅝", ".625", combine$Hands)
    combine$Hands = gsub("¾", ".75", combine$Hands)
    combine$Hands = gsub("⅞", ".875", combine$Hands)
    
    
    combine$Hands <- as.numeric(combine$Hands)
    

提交回复
热议问题