Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

The below are by 'a' and 'b':

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

b <- c("A", "C", "A")

I wanted to subset 'a' with respect to 'b' so that I can get the following set of values:

("B"  "A"  "B")

So what I want is while performing the subset of 'a' with respect to 'b' only two "A"s and one "C" should be removed from set a. And all of the rest of the elements that are in 'a' should remain even though they might be "A" or "C".

1 Answer

0 votes
by (108k points)

You can follow the below code, that may help you to reach  your target output:

#Count occurrences of `a`

a_count <- table(a)

#Count occurrences of `b`

b_count <- table(b)

#Subtract the count present in b from a 

a_count[names(b_count)] <- a_count[names(b_count)] - b_count

#Create a new vector of remaining values 

rep(names(a_count), a_count)

#[1] "A" "B" "B"

If you are new to R programming and you want to know more about R-programming, then do check-out the following R programming tutorial.

 

Browse Categories

...