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.
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.
To add string data to string vector you need write push_back(s), where s is string.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With