我正在尝试将风向(值0-360)转换为基本方向(即NW)。我的代码如下:
DegToDer <- function(degree) {
value <- as.integer((degree / 45)+ .5)
direction <- c("N","NE","E","SE","S","SW","W","NW")
return(direction[((value+1) %% 8)])}
在列上运行它时,出现以下错误:
替换有346行,数据有365
我已经用几个值对其进行了测试,发现应该返回值“ NE”的所有东西都只返回“ character(0)”
> DegToDer(293)
character(0)
> DegToDer(292)
[1] "W"
> DegToDer(360)
[1] "N"
在此问题上的任何协助都将不胜感激!
答案 0 :(得分:1)
因此,这里的问题是R索引向量从1开始,因此如果您提供的值像floor((293/45)+0.5)+1
一样返回8,则索引将是0,函数返回值将是NA
您如何尝试使用基本的R函数cut
?
DegToDer <- function (degree) {
return(cut(
x = degree,
breaks = c(0, seq(22.5, 337.5, 45), 360),
labels = c("N","NE","E","SE","S","SW","W","NW","N"),
include.lowest = TRUE
))
}
答案 1 :(得分:0)
您的%%
公式有误。
degree <- 0:90
DegToDer <- function(degree) {
value <- as.integer(degree / 45 + 0.5)
direction <- c("N","NE","E","SE","S","SW","W","NW")
return(direction[(value %% 8) + 1])
}
table(DegToDer(degree))
#>
#> E N NE
#> 23 23 45
由reprex package(v0.3.0)于2019-11-04创建