Search code examples
rapplycpu-wordsentence

converting a vector of sentences to vector of words using apply functions


In R, I have this vector of sentences and I would like to convert it to a vector of words. how can i do it using apply functions?

test.sentences <- c("boy who boys see lives .",
                    "cats who Mary feeds hear .",
                    "girls who see see John .",
                    "John hears dogs .",
                    "John lives .",
                    "Mary hears cat .",
                    "boys who Mary chases see girl .",
                    "dog who John sees feeds Mary .",
                    "girls feed cats who see .",
                    "Mary chases girls who Mary chases .",
                    "Mary hears .",
                    "boy who hears cats walks .",
                    "girl who dog sees feeds boy .",
                    "Mary lives .",
                    "Mary sees boy .",
                    "cat who walks lives .",
                    "Mary sees girl who chases John .",
                    "John chases boys who boy hears .",
                    "cats hear boy who feeds boys .",
                    "girls who hear see cats who hear .",
                    "girls who cats feed chase John .",
                    "cat lives .",
                    "cats live ." )

Solution

  • In base R:

    res <- unlist(strsplit(test.sentences," "))
    res[res != "."]
    

    or

     unlist(strsplit(gsub("\\.","",test.sentences)," "))