Conditioned vector creation based on another vector

Viewed 41

I'm a new user in R. Considering the following vector example <- c (15 1 1 1 7 8 8 9 5 9 5), I would like to create two additional vectors, the first with only the repeated numbers and the second with numbers that are not repeated, something like:

example1 <- c (15, 7)

example2 <- c (1, 8, 9, 5)

Thank you for your support.

3 Answers

Using example shown reproducibly in the Note at the end dups is formed from the duplicated elements and singles is the rest, This always gives two vectors (one will be zero length if there are no duplicates of if there are no singles) and it uses the numeric values directly without converting them to character.

dups <- unique(example[duplicated(example)])
singles <- setdiff(example, dups)

dups
## [1] 1 8 9 5

singles
## [1] 15  7

Note

The input shown in the question was not valid R syntax so we provide the input reproducibly here:

example <- scan(text = "15 1 1 1 7 8 8 9 5 9 5", quiet = TRUE)

You can count the appereances of the values using table:

example <- c(15,1,1,1,7,8,8,9,5,9,5)
tt <- table(example)

The names of the table are the counted values, so you can write:

repeatedValues <- as.numeric(names(tt)[tt>1])
uniqueValues <- as.numeric(names(tt))[tt==1]

Here's a one-liner using rle that puts the resultant vectors in a list:

split(rle(sort(example))$values, rle(sort(example))$lengths < 2)
#> $`FALSE`
#> [1] 1 5 8 9

#> $`TRUE`
#> [1]  7 15
Related