65

我仍在学习如何将 SAS 代码翻译成 R,但我收到了警告。我需要了解我在哪里犯了错误。我想要做的是创建一个变量来总结和区分人口的 3 种状态:大陆、海外、外国人。我有一个包含 2 个变量的数据库:

  • 身份证国籍:(idnat法国,外国人),

如果idnat是法语,那么:

  • 身份证出生地:(idbp大陆、殖民地、海外)

我想将信息汇总idnatidbp一个名为的新变量中idnat2

  • 身份:k(大陆、海外、外国人)

所有这些变量都使用“字符类型”。

idnat2 列中的预期结果:

   idnat     idbp   idnat2
1  french mainland mainland
2  french   colony overseas
3  french overseas overseas
4 foreign  foreign  foreign

这是我想用 R 翻译的 SAS 代码:

if idnat = "french" then do;
   if idbp in ("overseas","colony") then idnat2 = "overseas";
   else idnat2 = "mainland";
end;
else idnat2 = "foreigner";
run;

这是我在 R 中的尝试:

if(idnat=="french"){
    idnat2 <- "mainland"
} else if(idbp=="overseas"|idbp=="colony"){
    idnat2 <- "overseas"
} else {
    idnat2 <- "foreigner"
}

我收到此警告:

Warning message:
In if (idnat=="french") { :
  the condition has length > 1 and only the first element will be used

有人建议我使用“嵌套ifelse”来代替它,但会收到更多警告:

idnat2 <- ifelse (idnat=="french", "mainland",
        ifelse (idbp=="overseas"|idbp=="colony", "overseas")
      )
            else (idnat2 <- "foreigner")

根据警告消息,长度大于 1,因此只考虑第一个括号之间的内容。对不起,但我不明白这个长度与这里有什么关系?有人知道我错在哪里吗?

4

9 回答 9

127

如果您使用任何电子表格应用程序,则有一个if()带有语法的基本函数:

if(<condition>, <yes>, <no>)

R中的语法完全相同ifelse()

ifelse(<condition>, <yes>, <no>)

与电子表格应用程序的唯一区别if()是 Rifelse()是矢量化的(将矢量作为输入并在输出时返回矢量)。考虑以下电子表格应用程序和 R 中的公式比较,作为一个示例,我们希望比较 a > b,如果是则返回 1,否则返回 0。

在电子表格中:

  A  B C
1 3  1 =if(A1 > B1, 1, 0)
2 2  2 =if(A2 > B2, 1, 0)
3 1  3 =if(A3 > B3, 1, 0)

在 R 中:

> a <- 3:1; b <- 1:3
> ifelse(a > b, 1, 0)
[1] 1 0 0

ifelse()可以以多种方式嵌套:

ifelse(<condition>, <yes>, ifelse(<condition>, <yes>, <no>))

ifelse(<condition>, ifelse(<condition>, <yes>, <no>), <no>)

ifelse(<condition>, 
       ifelse(<condition>, <yes>, <no>), 
       ifelse(<condition>, <yes>, <no>)
      )

ifelse(<condition>, <yes>, 
       ifelse(<condition>, <yes>, 
              ifelse(<condition>, <yes>, <no>)
             )
       )

要计算列idnat2,您可以:

df <- read.table(header=TRUE, text="
idnat idbp idnat2
french mainland mainland
french colony overseas
french overseas overseas
foreign foreign foreign"
)

with(df, 
     ifelse(idnat=="french",
       ifelse(idbp %in% c("overseas","colony"),"overseas","mainland"),"foreign")
     )

R 文档

是什么the condition has length > 1 and only the first element will be used?让我们来看看:

> # What is first condition really testing?
> with(df, idnat=="french")
[1]  TRUE  TRUE  TRUE FALSE
> # This is result of vectorized function - equality of all elements in idnat and 
> # string "french" is tested.
> # Vector of logical values is returned (has the same length as idnat)
> df$idnat2 <- with(df,
+   if(idnat=="french"){
+   idnat2 <- "xxx"
+   }
+   )
Warning message:
In if (idnat == "french") { :
  the condition has length > 1 and only the first element will be used
> # Note that the first element of comparison is TRUE and that's whay we get:
> df
    idnat     idbp idnat2
1  french mainland    xxx
2  french   colony    xxx
3  french overseas    xxx
4 foreign  foreign    xxx
> # There is really logic in it, you have to get used to it

我还能用if()吗?是的,你可以,但语法不是很酷:)

test <- function(x) {
  if(x=="french") {
    "french"
  } else{
    "not really french"
  }
}

apply(array(df[["idnat"]]),MARGIN=1, FUN=test)

如果你熟悉 SQL,你也可以使用package中的CASE 语句sqldf

于 2013-08-02T12:27:37.383 回答
13

尝试以下操作:

# some sample data
idnat <- sample(c("french","foreigner"),100,TRUE)
idbp <- rep(NA,100)
idbp[idnat=="french"] <- sample(c("mainland","overseas","colony"),sum(idnat=="french"),TRUE)

# recoding
out <- ifelse(idnat=="french" & !idbp %in% c("overseas","colony"), "mainland",
              ifelse(idbp %in% c("overseas","colony"),"overseas",
                     "foreigner"))
cbind(idnat,idbp,out) # check result

您的困惑来自 SAS 和 R 如何处理 if-else 结构。在 R 中,if并且else不是矢量化的,这意味着它们检查单个条件是否为真(即if("french"=="french")有效)并且不能处理多个逻辑(即if(c("french","foreigner")=="french")无效),并且 R 会向您发出您收到的警告。

相比之下,ifelse它是矢量化的,因此它可以获取您的矢量(也称为输入变量)并测试其每个元素的逻辑条件,就像您在 SAS 中习惯的那样。解决这个问题的另一种方法是使用ifandelse语句构建一个循环(正如您在此处开始所做的那样),但矢量化ifelse方法将更有效并且通常涉及更少的代码。

于 2013-08-02T08:47:40.963 回答
9

data.table如果数据集包含许多行,则使用查找表而不是嵌套连接可能更有效ifelse()

提供下面的查找表

lookup
     idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

和一个样本数据集

library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
                 idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
      idnat     idbp
 1:  french   colony
 2:  french   colony
 3:  french overseas
 4: foreign  foreign
 5:  french mainland
 6: foreign  foreign
 7: foreign  foreign
 8:  french overseas
 9:  french overseas
10:  french mainland

然后我们可以在加入时进行更新

DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
      idnat     idbp   idnat2
 1:  french   colony overseas
 2:  french   colony overseas
 3:  french overseas overseas
 4: foreign  foreign  foreign
 5:  french mainland mainland
 6: foreign  foreign  foreign
 7: foreign  foreign  foreign
 8:  french overseas overseas
 9:  french overseas overseas
10:  french mainland mainland
于 2017-09-29T07:47:25.203 回答
8

您可以创建idnat2没有if和的向量ifelse

该函数replace可用于替换所有出现的"colony"with "overseas"

idnat2 <- replace(idbp, idbp == "colony", "overseas")
于 2013-08-02T16:18:25.193 回答
6

将 SQL CASE 语句与 dplyr 和 sqldf 包一起使用:

数据

df <-structure(list(idnat = structure(c(2L, 2L, 2L, 1L), .Label = c("foreign", 
"french"), class = "factor"), idbp = structure(c(3L, 1L, 4L, 
2L), .Label = c("colony", "foreign", "mainland", "overseas"), class = "factor")), .Names = c("idnat", 
"idbp"), class = "data.frame", row.names = c(NA, -4L))

sqldf

library(sqldf)
sqldf("SELECT idnat, idbp,
        CASE 
          WHEN idbp IN ('colony', 'overseas') THEN 'overseas' 
          ELSE idbp 
        END AS idnat2
       FROM df")

dplyr

library(dplyr)
df %>% 
mutate(idnat2 = case_when(idbp == 'mainland' ~ "mainland", 
                          idbp %in% c("colony", "overseas") ~ "overseas", 
                         TRUE ~ "foreign"))

输出

    idnat     idbp   idnat2
1  french mainland mainland
2  french   colony overseas
3  french overseas overseas
4 foreign  foreign  foreign
于 2017-02-08T08:33:17.550 回答
2

使用 data.table,解决方案是:

DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign", 
        ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]

ifelse是矢量化的。if-else不是。在这里,DT 是:

    idnat     idbp
1  french mainland
2  french   colony
3  french overseas
4 foreign  foreign

这给出了:

   idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign
于 2016-09-19T09:22:52.337 回答
1

示例的解释是帮助我的关键,但我遇到的问题是当我复制它时不起作用,所以我不得不以多种方式对其进行处理以使其正常工作。(我是 R 的超级新手,由于缺乏知识,我对第三个 ifelse 有一些问题)。

所以对于那些对 R 非常陌生的人遇到问题......

   ifelse(x < -2,"pretty negative", ifelse(x < 1,"close to zero", ifelse(x < 3,"in [1, 3)","large")##all one line
     )#normal tab
)

(我在一个函数中使用了它,所以它“ifelse ...”被标记在一个上面,但最后一个“)”完全在左边)

于 2020-02-12T21:34:42.840 回答
1
# Read in the data.

idnat=c("french","french","french","foreign")
idbp=c("mainland","colony","overseas","foreign")

# Initialize the new variable.

idnat2=as.character(vector())

# Logically evaluate "idnat" and "idbp" for each case, assigning the appropriate level to "idnat2".

for(i in 1:length(idnat)) {
  if(idnat[i] == "french" & idbp[i] == "mainland") {
    idnat2[i] = "mainland"
} else if (idnat[i] == "french" & (idbp[i] == "colony" | idbp[i] == "overseas")) {
  idnat2[i] = "overseas"
} else {
  idnat2[i] = "foreign"
} 
}

# Create a data frame with the two old variables and the new variable.

data.frame(idnat,idbp,idnat2) 
于 2018-08-28T08:30:02.490 回答
-1

很抱歉加入派对太晚了。这是一个简单的解决方案。

#building up your initial table
idnat <- c(1,1,1,2) #1 is french, 2 is foreign

idbp <- c(1,2,3,4) #1 is mainland, 2 is colony, 3 is overseas, 4 is foreign

t <- cbind(idnat, idbp)

#the last column will be a vector of row length = row length of your matrix
idnat2 <- vector()

#.. and we will populate that vector with a cursor

for(i in 1:length(idnat))

     #*check that we selected the cursor to for the length of one of the vectors*

{  

  if (t[i,1] == 2) #*this says: if idnat = foreign, then it's foreign*

    {

      idnat2[i] <- 3 #3 is foreign

    }

  else if (t[i,2] == 1) #*this says: if not foreign and idbp = mainland then it's mainland*

    {

      idnat2[i] <- 2 # 2 is mainland  

    }

  else #*this says: anything else will be classified as colony or overseas*

    {

      idnat2[i] <- 1 # 1 is colony or overseas 

    }

}


cbind(t,idnat2)
于 2019-01-03T04:29:36.420 回答