R: Converting data frame of percentages from factor to numeric

前端 未结 4 510
失恋的感觉
失恋的感觉 2021-01-22 15:50

Running into issues converting a data frame into R.

I have a bunch of columns that were read as factors and have % symbols with them.

I

4条回答
  •  渐次进展
    2021-01-22 16:04

    Try this approach using functions from base:

    # dummy data:
    df<-data.frame(v1=c("78%", "65%", "32%"), v2=c("43%", "56%", "23%"))
    
    # function
    df2<-data.frame(lapply(df, function(x) as.numeric(sub("%", "", x))) )
    

    As per the comments provided this first strips away the percentage signs, and then converts the columns from factors to numeric. I've changed the original answer from apply to lapply following @thelatemail's suggestions.

提交回复
热议问题