简体   繁体   English

if 和 else 与向量和条件不能正常工作

[英]if and else with vector sum condition not properly working

I have a data.frame called sites_sp where I'm trying to run some functions based on if and else statements.我有一个名为data.framesites_sp ,我试图在其中运行一些基于ifelse语句的函数。 sites_sp has the following structure: sites_sp具有以下结构:

structure(list(x = c(-50.1298257841559, -49.9523708108406, -49.8600298829818, 
-49.8590735594872, -49.8600022102151, -49.680556540172), y = c(-29.2498490060132, 
-29.1594734717135, -29.0700140387022, -28.9795033961473, -28.8900003372153, 
-28.8945716273705), ua = c("ua_1", "ua_4", "ua_10", "ua_15", 
"ua_21", "ua_23"), occ = c(0, 0, 0, 0, 0, 0), PC1 = c(0.403336553595704, 
-0.209623013249306, -2.38969068562858, -1.0875631345167, 0.0424075103800285, 
-1.69180948954307), PC2 = c(-3.62346919232857, -4.03856503375702, 
-1.46862258765078, -1.77908267718137, -2.0250031837701, -0.952927464794925
), PC3 = c(-0.375601733371977, -0.122982261539736, -0.365818414058142, 
-0.111150398019996, 0.287459840686463, 0.034973266100254), PC4 = c(-1.31153262462204, 
-0.899941801783298, -1.35652371929479, -1.98693913441246, -1.75393016363327, 
-0.788097574287776), PC5 = c(1.42830395246321, 1.55155187773266, 
1.33933059031444, 0.0760013457702872, 0.588191290690648, -0.408003273953271
)), row.names = c(NA, 6L), class = "data.frame")

What I'm doing is an if and else statements of form:我正在做的是一个ifelse形式的陈述:

for(s in sp){ 
 
if(sum(sites_sp$occ >= 30)){

     pa_data <- st_as_sf(sites_sp, 
                    coords = c("x", "y"), 
                    crs = crs(env_terra))
    ...

    } else {

    block of functions for the statement being FALSE

    }

}

RELEVANT EDIT: From what I can tell, the function is going directly to the else block even though it should not — since sum(sites_sp$occ) is bigger than 30 for the first s in sp相关编辑:据我所知,function 将直接进入else块,即使它不应该 - 因为sum(sites_sp$occ)对于s in sp大于 30

I can't really understand what's going on.我真的不明白发生了什么。 If I try sum(sites_sp$occ) it returns for me a value of 37, implying that the function inside the if block ( pa_data <- st_as_sf()... ) should run normally.如果我尝试sum(sites_sp$occ)它为我返回一个值 37,这意味着if块( pa_data <- st_as_sf()... )内的 function 应该正常运行。 What am I doing wrong here?我在这里做错了什么? If more information is needed, please tell me.如果需要更多信息,请告诉我。

Ok, guys...I'm kinda dumb.好吧,伙计们……我有点笨。

The problem is simply here:问题就在这里:

if(sum(sites_sp$occ >= 30)){

Should be written as应该写成

if(sum(sites_sp$occ) >= 30){

My condition was inside the sum我的条件在sum

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

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