简体   繁体   English

R function 返回“字符(0)”而不是基本方向

[英]R function is returning “Character (0)” instead of Cardinal Direction

I am attempting to convert wind direction (values 0-360) into a cardinal direction (ie NW).我正在尝试将风向(值 0-360)转换为基本方向(即 NW)。 My code is below:我的代码如下:

DegToDer <- function(degree) {
  value <- as.integer((degree / 45)+ .5)
  direction <- c("N","NE","E","SE","S","SW","W","NW")
  return(direction[((value+1) %% 8)])}

When I run it on my column I get the following error:当我在我的专栏上运行它时,我收到以下错误:

replacement has 346 rows, data has 365替换有 346 行,数据有 365

I've tested it out with a few values and found out that every thing that should return the value "NE" is only returning "character (0)"我已经用几个值对其进行了测试,发现应该返回值“NE”的每件事都只返回“字符(0)”

> DegToDer(293)
character(0)
> DegToDer(292)
[1] "W"
> DegToDer(360)
[1] "N"

Any and all assistance on this issue is greatly appreciated!非常感谢有关此问题的任何和所有帮助!

So, the problem here is that R indexes vectors starting at 1, so if you provide a value like floor((293/45)+0.5)+1 that returns 8, your index will be 0 and the function return value will be NA所以,这里的问题是 R 索引从 1 开始的向量,所以如果你提供像floor((293/45)+0.5)+1这样返回 8 的值,你的索引将是 0 并且 function 返回值将是NA

How about you try to work with the base R function cut ?您如何尝试使用基础 R function 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
  ))
}

You %% formula is slightly wrong.你的%%公式有点错误。

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

Created on 2019-11-04 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2019 年 11 月 4 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM