将一个扇区分配给R中的一个角度

assign a sector to an angle in R

我有一个介于 0 和 360 之间的开始和结束角度值的向量。 我想要一个额外的列来指定哪个扇区(考虑 12 个扇区)是我的变量。

扇区应定义为:(15:45], (45,75],(75,105], ..., (345,15]

test = structure(list(start = c(4, 67, 13, 35, 54, 0), end = c(23, 84, 
30, 52, 71, 0)), row.names = 2:7, class = "data.frame")

对于我的测试示例,我认为我必须遍历行数:

for( i in 1:nrow(test)){
  if(test$start[i] <= 15 | test$start[i] >345){test$sector_start[i] = 12}
  else if(test$start[i] > 15 & test$start[i] <= 45){test$sector_start[i] = 1}
  else if(test$start[i] > 45 & test$start[i] <= 75){test$sector_start[i] = 2}
  else if(test$start[i] > 75 & test$start[i] <= 105){test$sector_start[i] = 3}
  else if(test$start[i] > 105 & test$start[i] <= 135){test$sector_start[i] = 4}
  else if(test$start[i] > 135 & test$start[i] <= 165){test$sector_start[i] = 5}
  else if(test$start[i] > 165 & test$start[i] <= 195){test$sector_start[i] = 6}
  else if(test$start[i] > 195 & test$start[i] <= 225){test$sector_start[i] = 7}
  else if(test$start[i] > 225 & test$start[i] <= 255){test$sector_start[i] = 8}
  else if(test$start[i] > 255 & test$start[i] <= 285){test$sector_start[i] = 9}
  else if(test$start[i] > 285 & test$start[i] <= 315){test$sector_start[i] = 10}
  else if(test$start[i] > 315 & test$start[i] <= 345){test$sector_start[i] = 11}

  if(test$end[i] <= 15 | test$end[i] >345){test$sector_end[i] = 12}
  else if(test$end[i] > 15 & test$end[i] <= 45){test$sector_end[i] = 1}
  else if(test$end[i] > 45 & test$end[i] <= 75){test$sector_end[i] = 2}
  else if(test$end[i] > 75 & test$end[i] <= 105){test$sector_end[i] = 3}
  else if(test$end[i] > 105 & test$end[i] <= 135){test$sector_end[i] = 4}
  else if(test$end[i] > 135 & test$end[i] <= 165){test$sector_end[i] = 5}
  else if(test$end[i] > 165 & test$end[i] <= 195){test$sector_end[i] = 6}
  else if(test$end[i] > 195 & test$end[i] <= 225){test$sector_end[i] = 7}
  else if(test$end[i] > 225 & test$end[i] <= 255){test$sector_end[i] = 8}
  else if(test$end[i] > 255 & test$end[i] <= 285){test$sector_end[i] = 9}
  else if(test$end[i] > 285 & test$end[i] <= 315){test$sector_end[i] = 10}
  else if(test$end[i] > 315 & test$end[i] <= 345){test$sector_end[i] = 11}
}

在这里我可以向 test 添加 2 列,它告诉我我的角度在哪个扇区。我正在寻找一种更智能的方法,我可以选择改变扇区的数量,例如 24 个扇区。

正如 Roman 所说,您可以使用 cut。最后一步是角度 > 345 或 <= 15。

library(dplyr)
test %>% 
  mutate(sector_start = cut(start, 15 + 30*(0:11), 1:11)
         , sector_end = cut(end, 15 + 30*(0:11), 1:11)) %>% 
  mutate_at(vars(contains('sector')), ~ifelse(is.na(.), 12, .))

在基础 R 中:

test[paste0('sector_', names(test))] <- 
  lapply(test, function(x){
    labs <- cut(x, 15 + 30*(0:11), 1:11)
    ifelse(is.na(labs), 12, labs)
  })