How do I access a position in a character array?

Asked

Viewed 419 times

3

The following code returns me a vector of 12 letters:

res <- "ACDEDEAEDCED"
res <- strsplit(res,"", FALSE)
View(res[4])

Error in . subset2(x, i, Exact = Exact) : out-of-bounded index

More when I try to access a specific position and gives error. I have tried many ways. Among them: res[1,4] and res[,4]...

1 answer

3

The function strsplit returns a list, so the vector res is a list, see:

res <- "ACDEDEAEDCED"
res <- strsplit(res,"", FALSE)
res
[[1]]
 [1] "A" "C" "D" "E" "D" "E" "A" "E" "D" "C" "E" "D"

If you want element 4 of the first element of the list, you can take it as follows:

res[[1]][4]
[1] "E"
  • One can use unlist(strsplit(res,"", FALSE)) or strsplit(res,"", FALSE)[[1]] for the final result to be a vector, with the first grouping all the results of the strsplit and the second holds only the first.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.