Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete specific items in a list based on numbers in another list in R

Tags:

list

r

element

I have two lists, one containing varying lengths of character values (dat) and the other with a single numeric value in each element (delete_n).

dat <- list(c("Apple", "Pear"), c("Red", "Blue", "Green"), c("Toyota", "Mazda"))
delete_n <- list(0, 2, 1)

The elements in the "delete_n" pair up with the elements in "dat" (delete_n[1] goes with dat[1], and so on). The "delete_n" numbers (0,2,1) tell me how many specific list items in each element I need to delete from the end of each row.

Based on the example, I'm looking for a solution that will delete 0 items from dat[1], delete "Blue" and "Green" from dat[2] and "Mazda" from dat[3].

I've tried first to match up the element numbers and then to identify the element list index by the variations of the following, with no success. mapply may be more appropriate, but again I'm unclear as to how to write the function() portion.

lapply(seq_along(dat), function(x) {
    sapply(seq_along(delete_n), function(y) {
        x[y]
    })
})
like image 713
Brian Avatar asked Jan 20 '26 15:01

Brian


2 Answers

mapply(function (x, n) {
    # x is an element of dat; n is an element of delete_n
    x[seq_len(length(x)-n)]
}, dat, delete_n)

Explanation:

mapply applies the function to each element of dat and delete_n, taken together (so all first elements, all second elements, etc).

seq_len(i) makes the vector 1:i, so seq_len(length(x)-n) selects all but the last n elements of x.

like image 162
mathematical.coffee Avatar answered Jan 23 '26 04:01

mathematical.coffee


I liked the mapply approach, but this was what seemed natural to me (after failing with negative zeroes anyway).

 mapply( head, dat, sapply(dat, length )- unlist(delete_n ))
#-------
[[1]]
[1] "Apple" "Pear" 

[[2]]
[1] "Red"

[[3]]
[1] "Toyota"
like image 40
IRTFM Avatar answered Jan 23 '26 04:01

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!