Home > Mobile >  Remove alphanumeric and special character from a string in R
Remove alphanumeric and special character from a string in R

Time:12-21

mydata.dt=

Candidate.index Score
1 0: most of the time (5-7days/week)
2 0: most of the time (5-7days/week)
3 NA
4 3 : less likely (less than 1 per day)
5 1: a moderate amount of time (3-4 days per week)
6 0: most of the time (5-7days per week)
7 2: some times (3-4 days per week)

Output desired---

mydata.dt=

Candidate.index Score
1 0
2 0
3 NA
4 3
5 1
6 0
7 2

Code used: The observations were in factors so converted them to character first-- mydata.dt [, Score := as.character(Score)] Then tried to remove the description of scores using this code--- mydata.dt$Score <- as.integer(gsub('[a-zA-Z]', '', mydata.dt$Score))

this gives a Warning message: In eval(ei, envir) : NAs introduced by coercion. Output all the observations in Score column were converted to NA

This may be a repeated question, I tried a lot using the codes available in the previous thread but it doesn't seem t work well for me. Please help.

CodePudding user response:

Just use sub here:

mydata.dt$Score <- sub("^(\\d ):.*$", "\\1", mydata.dt$Score)
  • Related