Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a vector of string to a vector of integer

Tags:

r

The following works as expected:

> as.integer(c("2","3"))
[1] 2 3

but when I try (using the stringr package):

> str_split("55,66,77",",")
[[1]]
[1] "55" "66" "77"
> as.integer(str_split("55,66,77",","))
Error: (list) object cannot be coerced to type 'integer'

Is there any other way to convert a string of form "55,66,77" into the vector with those three numbers? I'm a complete newbie and any hint to documentation about this would be highly appreciated.

like image 965
rwst Avatar asked Dec 22 '13 17:12

rwst


People also ask

How do you convert a string vector to an integer vector in C++?

You can use std::transform . Use a std::back_inserter to insert the values into the std::vector<int> . For the unary function, use a lambda expression that uses std::stoi to convert the strings to integers.

How do you convert a string to a vector?

To add string data to string vector you need write push_back(s), where s is string.

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


2 Answers

str_split returns a list. You have to access the correct list element:

as.integer(str_split("55,66,77",",")[[1]]) ## note the [[1]]
# [1] 55 66 77

Or you could use unlist to turn the complete list into a vector:

as.integer(unlist(strsplit("55,66,77",",")))
# [1] 55 66 77
like image 108
sgibb Avatar answered Oct 19 '22 19:10

sgibb


If you have a vector of strings and want the values for each, lapply will iterate through the list:

v <- c("55,66,77", "1,2,3")
lapply(str_split(v, ','), as.integer)
## [[1]]
## [1] 55 66 77
## 
## [[2]]
## [1] 1 2 3
like image 26
Matthew Lundberg Avatar answered Oct 19 '22 19:10

Matthew Lundberg