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]
})
})
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With