英文:
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 <- 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
得分: 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 <-
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", "")
)
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论