Nested ifelse statement

前端 未结 9 1223
逝去的感伤
逝去的感伤 2020-11-22 04:02

I\'m still learning how to translate a SAS code into R and I get warnings. I need to understand where I\'m making mistakes. What I want to do is create a variable which summ

相关标签:
9条回答
  • 2020-11-22 04:34
    # 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) 
    
    0 讨论(0)
  • 2020-11-22 04:35

    Sorry for joining too late to the party. Here's an easy solution.

    #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)
    
    0 讨论(0)
  • 2020-11-22 04:38

    You can create the vector idnat2 without if and ifelse.

    The function replace can be used to replace all occurrences of "colony" with "overseas":

    idnat2 <- replace(idbp, idbp == "colony", "overseas")
    
    0 讨论(0)
提交回复
热议问题