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

41 Views Asked by At

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

dat <- 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 <- ifelse(dat$p_value < 0.001, "Significance", "Not significance")

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 < 0.001 & dat$slope >= 0) {
  dat_sf$tendencia <- "Increase" 
} else if(dat$pvalue < 0.001 & dat$slope <= 0) {
  dat_sf$tendencia <- "Decrease" 
}  else if(dat$pvalue > 0.001) {
    dat_sf$tendencia <- "Not trend"
  }

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

1

There are 1 best solutions below

0
Jan On BEST ANSWER

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 <-
    ifelse(
        dat$p_value < 0.001 & dat$slope >= 0,
        "Increase",
        ifelse(
            dat$p_value < 0.001 & dat$slope <= 0,
            "Decrease",
            ifelse(dat$p_value > 0.001,
                   "Not trend", "")
        )
    )