0

I am struggling to get 2 separate strings from splitting a string using strsplit in R. I appreciate this is probably a very simple request but I can't seem to find an answer.

I have a string called x which looks like this:

"1.23e+05,1.3e+05"

I tried to split it using this code:

str_split <- strsplit(x,split= ',', fixed=TRUE)

which seem produces a list of length 1, with a character of : "1.23e+05" "1.3e+05"

However when I try and subset this using str_split[1] it just returns the whole thing.

What is the simplest solution to get 2 substrings from this results?

Thanks

geds133
  • 1,503
  • 5
  • 20
  • 52

2 Answers2

2

I would suggest the use of unlist() and save in a vector:

#Data
x <- "1.23e+05,1.3e+05"
#Split
str_split <- unlist(strsplit(x,split= ',', fixed=TRUE))
#Output
str_split[1]
str_split[2]

Output:

str_split[1]
[1] "1.23e+05"
str_split[2]
[1] "1.3e+05"
Duck
  • 39,058
  • 13
  • 42
  • 84
2

If you subset the list to access the first element contained within the list, you should get the behavior you expect:

str_split <- strsplit("1.23e+05,1.3e+05", split= ',', fixed=TRUE)
str_split[[1]]

[1] "1.23e+05" "1.3e+05"

The output is a character vector with two items in it. I don't see the need or use of having two separate variables here. But, in case you wanted that, you could just use:

exp1 <- str_split[[1]][1]
exp2 <- str_split[[1]][2]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360