创建用于趋势分析表的if语句:条件长度大于1时出现错误。

huangapple go评论67阅读模式
英文:

Creating if staments for trend analysis table: Error on the condition has length > 1

问题

if (dat$p_value < 0.001 & dat$slope >= 0) {
  dat_sf$tendencia <- "Increase" 
} else if(dat$p_value < 0.001 & dat$slope <= 0) {
  dat_sf$tendencia <- "Decrease" 
} else if(dat$p_value > 0.001) {
    dat_sf$tendencia <- "Not trend"
}
英文:

I'm trying to make an example for a table where you have the parameters to analyze the trend:

dat &lt;- data.frame(
x = c(-56.1645, -55.7594, -57.9515),  #Longitude
y = c(-34.9011, -34.9033, -31.7333),  # Latitude
slope = rnorm(3),                      # trend
p_value = c(0.002, 0.0001, 0.1)        # significance
)

Then I add a column to indicate if the trend is significant or not:

dat_sf$sig &lt;- ifelse(dat$p_value &lt; 0.001, &quot;Significance&quot;, &quot;Not significance&quot;)

So, now I need to add another column that contains information whether the trend is positive, negative or does not exist from the p_value and slope

I wrote it:

if (dat$p_value &lt; 0.001 &amp; dat$slope &gt;= 0) {
  dat_sf$tendencia &lt;- &quot;Increase&quot; 
} else if(dat$pvalue &lt; 0.001 &amp; dat$slope &lt;= 0) {
  dat_sf$tendencia &lt;- &quot;Decrease&quot; 
}  else if(dat$pvalue &gt; 0.001) {
    dat_sf$tendencia &lt;- &quot;Not trend&quot;
  }

But it gives me an error:in if (datos$p_value < 0.001 & datos$slope >= 0) { :
the condition has length > 1

答案1

得分: 2

错误发生是因为if()没有进行向量化处理。您可能希望改用ifelse()。使用这个函数,您可以类似这样修改dat

dat$tendencia <-
    ifelse(
        dat$p_value < 0.001 & dat$slope >= 0,
        "增加",
        ifelse(
            dat$p_value < 0.001 & dat$slope <= 0,
            "减少",
            ifelse(dat$p_value > 0.001,
                   "无趋势", "")
        )
    )

注意:我已将英文文本翻译为中文,但代码部分保持不变。

英文:

The error occurs because if() is not vectorised. You may instead want to use ifelse(). Using this, you could e.g. modify dat similar to

dat$tendencia &lt;-
    ifelse(
        dat$p_value &lt; 0.001 &amp; dat$slope &gt;= 0,
        &quot;Increase&quot;,
        ifelse(
            dat$p_value &lt; 0.001 &amp; dat$slope &lt;= 0,
            &quot;Decrease&quot;,
            ifelse(dat$p_value &gt; 0.001,
                   &quot;Not trend&quot;, &quot;&quot;)
        )
    )

huangapple
  • 本文由 发表于 2023年7月12日 23:28:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定