moodymudskipper
moodymudskipper

Reputation: 47310

What's the name of the first argument of `[`?

letter[2] is equivalent to '['(letters,i=2) , second argument is i.

What is the name of the first argument so the 2 following expressions would be equivalent ?

lapply(1:3,function(x){letters[x]})
lapply(1:3,`[`,param1 = letters) # param1 to be replaced with solution

Upvotes: 4

Views: 132

Answers (3)

moodymudskipper
moodymudskipper

Reputation: 47310

rlang::as_closure and purrr::as_mapper ,both based on rlang::as_function (see doc) will both convert [ to a function with named parameters:

lapply(1:3, purrr::as_mapper(`[`), .x = letters)
lapply(1:3, rlang::as_closure(`[`), .x = letters)
# [[1]]
# [1] "a"
# 
# [[2]]
# [1] "b"
# 
# [[3]]
# [1] "c"

Upvotes: 1

Aurèle
Aurèle

Reputation: 12819

You have to be could be more specific than "[", for instance:

lapply(1:3, `[.numeric_version`, x = letters)

# [[1]]
# [1] "a"
# 
# [[2]]
# [1] "b"
# 
# [[3]]
# [1] "c"

(Not sure [.numeric_version is the most appropriate, though... I'm digging a bit more)

Upvotes: 3

Onyambu
Onyambu

Reputation: 79228

For you to be able to define a function similar to the one above, you will have to pass two arguments to your function. The function [ does take various inputs. We can use Map instead of lapply to give it both the data where to extract from and the Indices to indicate the part of the data to be extracted:

  Map("[",list(letters),1:3)
 [[1]]
 [1] "a"

 [[2]]
 [1] "b"

 [[3]]
 [1] "c"

This is similar to what you have above. Hope this helps

Upvotes: 5

Related Questions