简体   繁体   中英

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?

You can "hide" the loop with

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

or similar with transform .

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]) 

不如@Frank的解决方案好,但它也能完成工作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM