Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused by a vapply function using grepl internally (Part of datacamp course)

hits <- vapply(titles,
           FUN = grepl,
           FUN.VALUE = logical(length(pass_names)),
           pass_names)

titles is a vector with titles such as "mr", pass_names is a list of names.

2 questions.

  1. I don't understand the resulting matrix hits
  2. I don't understand why the last line is pass_names nor what how I am supposed to know about these 4 arguments. Under ?vapply it specificies the x, FUN, FUN.VALUE but I cannot figure out how I am supposed to figure out that pass_names needs to be listed there.

I have looked online and could not find an answer, so I hope this will help others too. Thank you in advance for your answers, yes I am a beginner.


Extra info: This question uses the titanic package in R, pass_names is just titanic$Name, titles is just paste(",", c("Mr\\.", "Master", "Don", "Rev", "Dr\\.", "Major", "Sir", "Col", "Capt", "Jonkheer"))

like image 466
Alexis Drakopoulos Avatar asked Dec 17 '25 13:12

Alexis Drakopoulos


1 Answers

You're right to be a bit confused.

The vapply code chunk in your question is equivalent to:

hits <- vapply(titles,
               FUN = function(x) grepl(x, pass_names),
               FUN.VALUE = logical(length(pass_names)))

vapply takes a ... argument which takes as many arguments as are provided. If the arguments are not named (see @Roland's comment), the n-th argument in the ... position is passed to the n+1-th argument of FUN (the first argument to FUN is X, i.e. titles in this case).

The resulting matrix has the same number of rows as the number of rows in titanic and has 10 columns, the length of titles. The [i, j]-th entry is TRUE if the i-th pass_names matches the j-th regular expression in titles, FALSE if it doesn't.

like image 57
Hugh Avatar answered Dec 20 '25 06:12

Hugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!