Marvin
Marvin

Reputation: 21

Access the row number in lapply

I would like to access the current row number in a lapply-iteration:

lapply(dplyr::starwars$name[1:3], function(x){
  lapply(dplyr::starwars$name[2:4], function(y){
    paste(x,'&',y)
  })
})

In the second lapply-statement I need to access the following entry of the current first one, so instead of this output

x[1] - y[2]     Luke Skywalker & C-3PO
x[1] - y[3]     Luke Skywalker & R2-D2
x[1] - y[4]     Luke Skywalker & Darth Vader

x[2] - y[2]     C-3PO & C-3PO
x[2] - y[3]     C-3PO & R2-D2
x[2] - y[4]     C-3PO & Darth Vader

x[3] - y[2]     R2-D2 & C-3PO
x[3] - y[3]     R2-D2 & R2-D2
x[3] - y[4]     R2-D2 & Darth Vader

I would like to have this output to avoid getting the same row twice

x[1] - y[2]     Luke Skywalker & C-3PO
x[1] - y[3]     Luke Skywalker & R2-D2
x[1] - y[4]     Luke Skywalker & Darth Vader

x[2] - y[3]     C-3PO & R2-D2
x[2] - y[4]     C-3PO & Darth Vader

x[3] - y[4]     R2-D2 & Darth Vader

Is it possible to get the current row number (first lapply) back and put it into the second lapply?

Upvotes: 1

Views: 202

Answers (3)

e.matt
e.matt

Reputation: 886

result<-lapply(dplyr::starwars$name[1:3], function(x){
  lapply(dplyr::starwars$name[2:4], function(y){
if(x!=y) paste(x,'&',y) else NULL
  })
})
unlist(result)

Upvotes: 0

G5W
G5W

Reputation: 37641

One way to do it is to use lapply on the indices, but refer to the data inside the function

lapply(1:3, function(x){
    lapply((x+1):4, function(y){
        paste(dplyr::starwars$name[x],'&',dplyr::starwars$name[y])
    })
})

Upvotes: 1

lroha
lroha

Reputation: 34441

How about a different approach:

combn(starwars$name[1:4], 2, paste, collapse = " & ")

[1] "Luke Skywalker & C-3PO"       "Luke Skywalker & R2-D2"       "Luke Skywalker & Darth Vader" "C-3PO & R2-D2"                "C-3PO & Darth Vader"         
[6] "R2-D2 & Darth Vader"     

Upvotes: 1

Related Questions