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

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

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

问题

  1. if (dat$p_value < 0.001 & dat$slope >= 0) {
  2. dat_sf$tendencia <- "Increase"
  3. } else if(dat$p_value < 0.001 & dat$slope <= 0) {
  4. dat_sf$tendencia <- "Decrease"
  5. } else if(dat$p_value > 0.001) {
  6. dat_sf$tendencia <- "Not trend"
  7. }
英文:

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

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

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

  1. 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:

  1. if (dat$p_value &lt; 0.001 &amp; dat$slope &gt;= 0) {
  2. dat_sf$tendencia &lt;- &quot;Increase&quot;
  3. } else if(dat$pvalue &lt; 0.001 &amp; dat$slope &lt;= 0) {
  4. dat_sf$tendencia &lt;- &quot;Decrease&quot;
  5. } else if(dat$pvalue &gt; 0.001) {
  6. dat_sf$tendencia &lt;- &quot;Not trend&quot;
  7. }

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

  1. dat$tendencia <-
  2. ifelse(
  3. dat$p_value < 0.001 & dat$slope >= 0,
  4. "增加",
  5. ifelse(
  6. dat$p_value < 0.001 & dat$slope <= 0,
  7. "减少",
  8. ifelse(dat$p_value > 0.001,
  9. "无趋势", "")
  10. )
  11. )

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

英文:

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

  1. dat$tendencia &lt;-
  2. ifelse(
  3. dat$p_value &lt; 0.001 &amp; dat$slope &gt;= 0,
  4. &quot;Increase&quot;,
  5. ifelse(
  6. dat$p_value &lt; 0.001 &amp; dat$slope &lt;= 0,
  7. &quot;Decrease&quot;,
  8. ifelse(dat$p_value &gt; 0.001,
  9. &quot;Not trend&quot;, &quot;&quot;)
  10. )
  11. )

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:

确定