pedram
pedram

Reputation: 3087

How do I access a member of a list within a data.frame based on a column in the data.frame?

I have a data.frame, as below:

x <- structure(list(tsv_level = c(2, 3, 2, 3, 2, 2), tsv_payout = structure(list(
    c(0, 700, 1400, 2100, 2800), c(0, 300, 600, 900, 1200), c(0, 
    300, 600, 900, 1200), c(0, 3000, 6000, 9000, 12000), c(0, 
    700, 1400, 2100, 2800), c(0, 1000, 2000, 3000, 4000)), class = "AsIs")), .Names = c("tsv_level", 
"tsv_payout"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", 
"data.frame"))

I would like to create a 3rd column that returns the tsv_levelth element of each list within tsv_payout.

I can do this individually by doing this for row 1: x$tsv_payout[[1]][2], and x$tsv_payout[[2]][3] for row 2, but how can I do this for all rows in the data.frame?

Upvotes: 1

Views: 64

Answers (3)

989
989

Reputation: 12935

Not as good as @Frank's solution but it also does the job:

x$v <- sapply(seq_along(x$tsv_level), function(i) x$tsv_payout[[i]][x$tsv_level[i]])

Upvotes: 1

pedram
pedram

Reputation: 3087

Frank's answer works, and only relies on base R, but it also looks like rowwise() in the dplyr package will work here.

x %>% rowwise() %>%
    mutate(v = tsv_payout[tsv_level]) 

Upvotes: 1

Frank
Frank

Reputation: 66819

You can "hide" the loop with

x$v = with(x, mapply(`[[`, tsv_payout, tsv_level))

or similar with transform.

Upvotes: 3

Related Questions