I have a similar string to below from my shiny app via textAreaInput: Basically one can copy paste either numbers or names into the box.
It can be either seperated by emty space or line break.
When I read it is similar to the x as an example.
x <- "35 4.6 6.9 -0.4 -4.4"
#I can get each charcter with the following:
b<-stringr::str_split(x, boundary("word"))[[1]]
#but when the input is all numbers as seen in x, the negative signs disappear as below:
stringr::str_split(a, boundary("word"))[[1]]
[1] "35" "4.6" "6.9" "0.4" "4.4"
Is there a way to make sure I get the negative signs as well?
The reason I am using boundary("word") option is because it allows me to paste either with line break or with any number of spaces among elements.
Note: the solution should also work if x has only characters like this:
x <- "name1 name2 name3 name5"
stringr::str_split(x, boundary("word"))[[1]]
[1] "name1" "name2" "name3" "name5"
We can use scan
from base R
to read those as numeric
into a vector
x1 <- scan(text = x, what = numeric(), quiet = TRUE)
x1
#[1] 35.0 4.6 6.9 -0.4 -4.4
str(x1)
#num [1:5] 35 4.6 6.9 -0.4 -4.4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.