Tim Givois
Tim Givois

Reputation: 2014

Pass from literal string numeric to numeric in R

let's say I have

list_of_literals <- c('six', 'seven', 'eight' ... )

and I want to pass to

list_of_numerics <- c(6, 7, 9 ...)

I understand that I can map every possible string value to its numeric value, but, let's suppose that I don't have prior knowledge of the values, so mapping will be very inefficient, is there any package that already does this parsing?

Upvotes: 2

Views: 40

Answers (1)

akrun
akrun

Reputation: 887118

We can use english. Create an initial vector of numbers ('v1'), convert it to english and check whether it is %in% the 'list_of_literals' to get a logical vector and based on that subset the 'v1'

library(english)
v1 <- 1:10
v1[as.character(english(1:10)) %in% list_of_literals]
#[1] 6 7 8

data

list_of_literals <- c("six", "seven", "eight")

Upvotes: 2

Related Questions