1

Hey guys so im trying to convert a vector containing all factor values as shown in the image below to an integer vector:

image of vector

I have tried data$rate=as.numeric(data$rate) and this gives me the frequencies of all the ratings as num, and data$rate=as.numeric(as.character(data$rate)) gives me all NA values.

I'd like to convert to normal int or num thanks.

Lamanus
  • 12,898
  • 4
  • 21
  • 47
Wizzy
  • 15
  • 3
  • 1
    Does `as.numeric(sub("\\/5","",data$rate))` do what you want? – Edward Mar 02 '20 at 08:37
  • Hi WizArtifact. Please do not post images of code or data here! It yould be very easy for you to type out (or use `dput`) an example data. The solution to your problem is evaluating the parsed string. If you provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) I can give you a better answer. – dario Mar 02 '20 at 08:37
  • 1
    Also: How should `3.5/5` be converted to an integer? – dario Mar 02 '20 at 08:40
  • @Edward thank you so much that worked ! and sorry dario this was my first post so like was unsure of how to go about the post thanks for the tips will keep in mind for the next post ! – Wizzy Mar 02 '20 at 08:48

2 Answers2

0

Are you looking for something like this function?

factor2num <- function(x, parse = FALSE){
  s <- as.character(x)
  if(parse) eval(parse(text = s)) else as.numeric(s)
}

factor2num(factor("3"))    
#[1] 3

factor2num(factor("3.9/5"), TRUE)
# [1] 0.78
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0
data$rate <- as.numeric(sub("\\/5", "", data$rate))

This effectively replaces "/5" with "".

Edward
  • 10,360
  • 2
  • 11
  • 26