matloff / fasteR

Fast Lane to Learning R!
958 stars 154 forks source link

Unclear code and Your Turn in Lesson 29 #19

Closed khangquangtran closed 1 year ago

khangquangtran commented 1 year ago

I write: extractNonemptyWords(abt). The code runs.

In Lesson 29, the code:

extractNonemptyWords <- function(s) { z <- strsplit(s,' ')[[1]] z[z != ""] }

is supposed to split a text body into words (including empty words), then it takes the first line and returns the non-empty words. Is that right? If so, to me, this code is not useful much, since it only returns 1 line of non-empty words (the very first line) and the line choice is not a changeable argument, so I have to go to the function code and change [[1]] each time I want a different line of non-empty words.

Next is the Your Turn section right after the code:

Your Turn: That [[1]] expression in the body of extractNonemptyWords was crucial! Try the code without it, and see if you can explain the result, which is not what we desire. Tip: This illustrates a common error for beginners and veterans alike. The error message probably won't be helpful! So keep this frequent error in mind, both when you're writing code and viewing cryptic error messages.

What is the error that I should expect? And what is the desired result supposed to be? Only 1 line of non-empty words (the very first line of the text), or whole text of non-empty words?

P.S.: I have read Lesson 30 and see how to use extractNonemptyWords function, but is it a bit late to know how to use it? Shouldn't the example use of this function right below the function definition?