How to transform a vector list into R?

4

How to transform a vector list into R? The list is a set of words and numbers and I need to add the numbers in the list.

mylist <- list ("2 tomates", "5 tomates", "9 tomates")

If I want total tomatoes, how do I do it?

    
asked by anonymous 26.05.2014 / 01:08

1 answer

3

At least two ways - there are sure to be others:

# note a diferenca entre as listas
mylist <- list ("2 tomates", "5 tomates", "9 tomates")

first,

myvector <- unlist(mylist)
x = regmatches(myvector, regexpr("[0-9]+", myvector))
y = as.numeric(x)
sum(y)

or

numeros = function(x) {
  regmatches(x, regexpr("[0-9]+", x))[1]
}
x = unlist(lapply(mylist, numeros))
y = as.numeric(x)
sum(y)

Both answers assume that the regular expression "[0-9]+" is what you want.

In my answer, I assumed that mylist had 3 components, not one as in the original question.

    
26.05.2014 / 04:19