Home > database >  How to add a coulmn in r combining information from two columns?
How to add a coulmn in r combining information from two columns?

Time:10-06

I have this dataframe:

 Dat <- c("B", "A", "A", "B", "B")
 Nat <- c("B", "B", "A", "B", "A")

 df <- data.frame(Nat, Dat)

I want to a third comumne with

 res <- c("Both are B", "Only Dat is A", "Both are A", "Both are B", "Only Nat is A")

if both are B > Both are B

both are A > Both are A

if Dat is A > Only Dat is A

if Nat is A > Only Nat is A

desired output

out <- data.frame(Nat, Dat,res)

CodePudding user response:

fn <- function(x){
  if(x[1] == x[2]) paste('Both are', x[1])
  else if(x[1] == 'A') 'Only Nat is A'
  else 'Only Dat is A'
}

cbind(df, res = apply(df, 1, fn))
  Nat Dat           res
1   B   B    Both are B
2   B   A Only Dat is A
3   A   A    Both are A
4   B   B    Both are B
5   A   B Only Nat is A

CodePudding user response:

A simple way to do this is by combining information from the two columns using paste0(), and replace the combined values accordingly by using revalue() from the package plyr.

library(plyr)
library(magrittr)   ## For using the pipe %>%

temp <- paste0(Dat,Nat)   ## Combine the vectors element-wise

res <- temp %>% revalue(c("BB" = "Only B", 
                          "AA" = "Only A", 
                          "AB" = "Only Dat is A", 
                          "BA" = "Only Nat is B"))

cbind(df, res)

Hope this helps.

CodePudding user response:

Two possible solutions:

with(df, ifelse(Nat==Dat, 
                paste0("Both are ", Nat), 
                ifelse(Nat=="A", "Only Nat is A", "Only Dat is A")))

[1] "Both are B"    "Only Dat is A" "Both are A"    "Both are B"    "Only Nat is A"

Or

cases = c(BB="Both are B", AA="Both are A", AB="Only Dat is A", BA="Only Nat is A")
unname(cases[paste0(df$Dat, df$Nat)])
  •  Tags:  
  • r
  • Related