Marcin
Marcin

Reputation: 134

Access several elements from list based on the indexes stored in another list

What I am trying to do is to extract elements from data frame column that contains list, imagine column df$A with 3 rows, each rows contains list:

c(111, 222, 333)
c(444, 555, 666)
c(777, 888, 999)

(lists vary from one to twenty-thirty elements)

while column df$B stores certain positions of elements:

1
c(1, 2)
c(1, 2, 3)

my goal is to extract to column df$C elements from column df$B, based on their index stored in column df$A, so the column df$C would look like

111
c(444, 555)
c(777, 888, 999)

I've already tried different combinations of unlist, sapply, mutate, accessing list elements with vector, like

df$A[nrow][[c(df$B)]]

and so on, but I keep on running into different errors and haven't gotten closer to desired result.

Finally, what I want to achieve, is to sum integers in each row on certain position on a list, so potential df$D might look like

111
999
2664

I am afraid that maybe my entire approach is wrong and I am forcing R to act in a way it was not designed to, but so far I usually managed to get right answers for every question I've asked myself.

Upvotes: 0

Views: 22

Answers (1)

Andre Elrico
Andre Elrico

Reputation: 11480

not sure about the whole data.frame contains lists thing:

data: (not recommended though) just use two lists (l1 , l2)

df1 <- data.frame(A = 1:3)

df1$A <- list(c(111, 222, 333),
              c(444, 555, 666),
              c(777, 888, 999))

df1$B <- list(1,
              c(1, 2),
              c(1, 2, 3))

code: its time for ?mapply.

#df1$D <-
mapply(function(vals, inds) {sum(vals[inds])}, vals = df1$A, inds = df1$B)

result:

#[1]  111  999 2664

Upvotes: 1

Related Questions