R - 根据单独数据框中的间隔添加列

时间:2018-03-26 22:29:40

标签: r dataframe

我有以下数据框:

DF <- data.frame(Time=c(1:20))
StartEnd <- data.frame(Start=c(2,6,14,19), End=c(4,10,17,20))

我想添加一个列&#34;活动&#34;如果时间列中的值位于StartEnd数据帧中指定的一个间隔之间,则为DF。

我想出了以下内容:

mapply(FUN = function(Start,End) ifelse(DF$Time >= Start & DF$Time <= End, 1, 0), 
  Start=StartEnd$Start, End=StartEnd$End)

这并没有给我我想要的输出(它给了我一个有四列的矩阵),但是我想得到一个可以添加到DF的矢量。

我想解决方案很简单,但我没有看到它:)提前谢谢你。

编辑:我确定我可以使用循环,但我想知道是否有更优雅的解决方案。

2 个答案:

答案 0 :(得分:0)

您可以使用

实现此目的
DF$Activity <- sapply(DF$Time, function(x) {
  ifelse(sum(ifelse(x >= StartEnd$Start & x <= StartEnd$End, 1, 0)), 1, 0)
})

我希望这有帮助!

答案 1 :(得分:0)

如果你正在使用tidyverse,我认为一个好的方法可以与purrr::map2一起使用:

# generate a sequence (n, n + 1, etc.) for each StartEnd row
# (map functions return a list; purrr::flatten_int or unlist can
# squash this down to a vector!)
activity_times = map2(StartEnd$Start, StartEnd$End, seq) %>% flatten_int

# then get a new DF column that is TRUE if Time is in activity_times
DF %>% mutate(active = Time %in% active_times)