0

I have a variable containing university names in R:

mydata = data.frame(matrix(nrow=3))
mydata$uni <- c("University of Texas", "University of Washington", "Harvard University", "The Scripps Research Institute")

I want to end up with a variable, where the order of the words are reversed:

mydata$uni_revs <- c("Texas of University", "Washington of University", "University Havard", "Institute Research Scripps The")

I tried the approach described at the bottom of this page: https://www.codingprof.com/3-easy-ways-to-reverse-a-string-in-r/

mydata$string_split <- strsplit(mydata$uni, " ")
mydata$uni_revs2 <- paste(rev(mydata$string_split), collapse=" ")

It does not produced the desired results, as each row now simply contains "c(\"Harvard\", \"University\") c(\"University\", \"of\", \"Washington\") c(\"University\", \"of\", \"Texas\")" which is different from the results defined in mydata$uni_revs

EmilA
  • 11
  • 2
  • @benson23 ... but the sentence is not actually being fully reversed here. – Tim Biegeleisen Mar 17 '23 at 12:51
  • 1
    @TimBiegeleisen At least from OP's example they are fully reversed? Code taken from the dup link `mydata$uni_revs <- sapply(strsplit(mydata$uni, "\\s+"), function(x) paste(rev(x), collapse=" "))`, seems to have the desired output? I apologise in advance if I'm missing something here. – benson23 Mar 17 '23 at 12:54
  • 1
    I guess you could be right...the word `of` is in the middle. – Tim Biegeleisen Mar 17 '23 at 12:55
  • 1
    @TimBiegeleisen Actually I'm not sure what the OP wants. e.g. what should happen to universities with more than three words (university of southern california) – benson23 Mar 17 '23 at 12:58
  • @benson23 I just provided a 4 word example in my question, but to be sure, what I wanted in your example would be (california southern of university) – EmilA Mar 17 '23 at 13:03
  • 1
    @EmilA Try the code shown in my first comment :) – benson23 Mar 17 '23 at 13:04

0 Answers0