How to use apply to change the elements of one dataframe based in the columns of another?

蹲街弑〆低调 提交于 2020-03-25 18:37:28

问题


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!


回答1:


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



回答2:


We can also do this with map2

library(dplyr)
library(purrr)
df %>% 
   transmute(new = map2(b, e, `:`)) %>%
   pull(new) %>% 
   flatten_int %>%
   replace(logint, ., TRUE)


来源:https://stackoverflow.com/questions/60425315/how-to-use-apply-to-change-the-elements-of-one-dataframe-based-in-the-columns-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!