R 如何使用ifTHEN语句

R 如何使用ifTHEN语句,r,if-statement,dplyr,R,If Statement,Dplyr,我是R新手,尝试做简单的if/then语句。使用dataframeDFnew,我想执行: if "location2" is not missing then "Location" = "location2" 我的代码: library(dplyr) test %>% DFnew %>% if(location2 != NA){ Location <- location2 } 库(dplyr)

我是R新手,尝试做简单的if/then语句。使用dataframe
DFnew
,我想执行:

if "location2" is not missing then "Location" = "location2" 
我的代码:

library(dplyr)

test %>% DFnew %>%
  if(location2 != NA){
    Location <- location2
  } 
库(dplyr)
测试%>%DFnew%>%
如果(位置2!=NA){

位置使用矢量化函数
ifelse
if_else
如果使用
dplyr
。要检查
NA
值,请使用函数
is.NA

library(dplyr)

DFnew %>% mutate(Location = if_else(!is.na(location2), location2, Location))
使用
coalesce
也可以达到同样的效果,如下所示:

DFnew %>% mutate(Location = coalesce(location2, Location))

library(dplyr)
DFnew %>%
      mutate(Location = case_when(!is.na(location2) ~ location2, TRUE ~ location))

请包含必要的
library()
语句,以使此代码可复制;您的代码意味着您正在使用
dplyr
,因为否则将数据帧列引用为“location2”,“
Location
将要求您编写
DFnew[/Location']
然后,您需要解释“location2”、“Location”是DF中的简单变量还是列名。可能是后者。在这种情况下,您需要将if-Then表达式和赋值矢量化。