multiphrenic multiphrenic - 3 months ago 9
R Question

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?

Answer

You can "hide" the loop with

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

or similar with transform.