How to insert in Vectorize `[`

I am unable to get Vectorizeto work with [, having received the error below. Of help("[")it seems to [have arguments with a name x, iand j- but they do not work when I used them as vectorize.args. Can I do it?

## Some data
dat <- data.frame(a=1:10, b=11:20, c=21:30)

## Vectorize with mapply, seems to work
f <- function(i, j, dat) list(dat[i, j])
mapply(f, list(1:2, 3:4), list(1:2, 2:3), MoreArgs = list(dat=dat))
# [[1]]
#   a  b
# 1 1 11
# 2 2 12
# 
# [[2]]
#    b  c
# 3 13 23
# 4 14 24

## Now using Vectorize, apply to data
Vectorize(`[`, c("i", "j"))(x=dat, i=list(1:2, 2:3), j=list(1:2, 2:3))

Error in Vectorize ( [, c ("i", "j")): must indicate formal argument names for 'vectorize'

But this works (with a warning about argument names)

`[`(x=dat, i=1:2, j=1:2)

Also, if I do, it’s normal

Vectorize(`[.data.frame`, c("i", "j"))(dat, list(1:2, 2:3), list(1:2, 2:3))
+4
source share
1 answer

Vectorize()documented so that it cannot be used with primitive functions. Of?Vectorize

 ‘Vectorize’ cannot be used with primitive functions as they do not
 have a value for ‘formals’.

[ R:

> `[`
.Primitive("[")

[ , . `[`(x=dat, i=1:2, j=1:2) :

dat[1:2, 1:2]

> dat[1:2, 1:2]
  a  b
1 1 11
2 2 12

( ) :

i <- 1:2
j <- 1:2
dat[i, j]

> dat[i, j]
  a  b
1 1 11
2 2 12

, , [.data.frame Vectorise. ?Vectorize rep(), , rep.int().

+10

All Articles