Home > Net >  How to verify duplication before append data in r
How to verify duplication before append data in r

Time:12-02

I want to append data to my list only if it is distinct from previously stored data.

data <- c("A","B","C")

My code so far:

x<- function(...){
  
  data <- ifelse(... %in% data, append(data, ""),append(data, as.character(...)))
  return(data)
  
}

For instance, if I want to append "D," my desired output is:

data
[1] "A" "B" "C" "D"
  

However, I received this:

 data
 [1] "A"

CodePudding user response:

x <- c("A","B","C")
y <- c("D", "A")

union(x, y)

# [1] "A" "B" "C" "D"

CodePudding user response:

ifelse function cannot give vector as a result. See ifelse function documentation.

Instead, you should use if - else statement

x<- function(...){
  
  data <- if (... %in% data) {append(data, "")} else {append(data, as.character(...))}
  return(data)
  
}

x("D")

[1] "A" "B" "C" "D"

CodePudding user response:

Here is my solution:

x <- c("A","B","C")
y <- c("D", "A")

unique(c(x, y))

[1] "A" "B" "C" "D"
  • Related