如何使用 apply 更改一个数据框的元素基于另一个数据框的列? [英] How to use apply to change the elements of one dataframe based in the columns of another?
问题描述
我有一个数据框,其中两列标记了我需要在另一个数据框中操作的区域的开始和结束.而不是应用 for 我决定用我感兴趣的行创建一个逻辑向量
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)})
然而,结果是一个矩阵,df
的每一行都有一列.我知道我可以用
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))
但是如果df
中的行数太大,则没有足够的内存来分配apply产生的矩阵.
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?
谢谢!
推荐答案
我们可以使用 mapply
/Map
在 b
之间创建一个序列和 e
值并将它们转换为 TRUE
.
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
这篇关于如何使用 apply 更改一个数据框的元素基于另一个数据框的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!