I have a sentence, ['this', 'is, 'my', house']. After splitting it by using "-"as a as separator,and reversing it to[ house, my, is, this], how do I access the last part of string? and join my and is together with house to form another sentence?
Asked
Active
Viewed 1,997 times
2 Answers
1
out <- strsplit(sentence, "-")
last <- out[length(out)]
flip <- rev(last)
word <- paste(flip, collapse='')

DBD
- 86
- 3
-
@Rich, it is not giving me esuoh but it is giving me 'house' I tried it just now – rjrj Mar 21 '17 at 00:13
1
sentence <- c("this","is","my","house")
strsplit(sentence[4], split="")[[1]][nchar(sentence[4]):1]
This code might be a bit dense for a beginner to interpret. The [[1]]
is necessary because the value of strsplit
is always a list, even when it's just one vector of individual characters; the indexing extracts that vector. The indexing after that, [nchar(sentence[4]):1]
, reorders the letters in that vector backwards, from the last to the first, in this case c(5,4,3,2,1)
. The split=""
argument causes the strsplit
function to split the string at every possible point, i.e. between each character.

DHW
- 1,157
- 1
- 9
- 24