Reputation: 430
I have a data frame where two columns mark the beginning and end of regions I need to manipulate in another data frame. Instead of applying a for I decided to create a logical vector with the rows I'm interested
df <- data.frame(b=c(7,25,32,44),e=c(11,27,39,48),n=c('a','b','c','d'))
logint <- rep(F,50)
log_vec <- apply(df[,c('b','e')],1, function(x){logint[x['b']:x['e']] <- T;return(logint)})
However, the result a matrix with one column for each row of df
. I know I can solve this with
log_vec <- Reduce(`|`,as.data.frame(log_vec))
but if the number of rows in df
is too large, there is not enough memory to allocate the matrix resulting from apply.
Do you have a better solution?
Thanks!
Upvotes: 0
Views: 37
Reputation: 887128
We can also do this with map2
library(dplyr)
library(purrr)
df %>%
transmute(new = map2(b, e, `:`)) %>%
pull(new) %>%
flatten_int %>%
replace(logint, ., TRUE)
Upvotes: 0
Reputation: 388982
We can use mapply
/Map
to create a sequence between b
and e
values and turn them to TRUE
.
logint <- rep(FALSE,50)
logint[unlist(Map(`:`, df$b, df$e))] <- TRUE
Upvotes: 2