Intersect Vectors


Does anyone know how to intersect 2 vectors to resolve the following use case with vectors of different lengths?

d$Id <- c(1,2,3,4,5)
s$Id <- c(3,5)

I want to return a new value which is the length of d (five) with a new value d$color where if 3 or 5 the color is red else the color is steelblue. Thus, the final vector I'm looking for is:

d$color <- c(steelblue, steelblue, red, steelblue, red)

I tried the %in% within ifelse statements without success.

thank you

How did it fail? I'd expect it to work, what code did you use, and what error message did you get?

its not clear how your text description involving d involves s at all, what is the relevance of s to this ?

How about this:

d$color = rep("steelblue", length(d$Id))
d$color[d$Id %in% s$Id]="red"


Thanks all, as a relative newbie to R my use case is taking a dataframe 'd' and subsetting this based on selected rows in a DT table in shiny using the selected rows feature. All of this works fine, I have a large dataframe d and a subset of d called s. I then have a ggplot of points showing all d and want to highlight the selected points from the table which are s in d. I know how to do all of this using DT and ggplot, and for reasons beyond this post I don't want to use the brush feature.

I simply want to have a new column in d which indicates 'color' which will then highlight my points in the ggplot. Hence, I want to set the color of my points c(1,2,3,4,5....) in d based on what is selected in s c(3,5...). So, I'd like 1,2,4 to be steelblue and 3 and 5 to be red.

Here's a simple example

d <- data.frame(Id = c(1,2,3,4,5))
s <- data.frame(Id = c(3,5))

x1 <- if(s$Id %in% d$Id){"red"}else{"steelblue"}
error: the condition has length > 1 and only the first element will be used
[1] "red"

or try
x2 <- ifelse(s$Id %in% d$Id,"red","steelblue")
[1] "red" "red"

Thanks again!

You basically have it: the first one doesn't work because if{}else{} is not vectorized. The second approach is correct, you just need to look if d is in s, rather than the opposite.

d <- data.frame(Id = c(1,2,3,4,5))
s <- data.frame(Id = c(3,5))

x1 <- ifelse(d$Id %in% s$Id, "red", "steelblue")
#> [1] "steelblue" "steelblue" "red"       "steelblue" "red"

Created on 2020-11-26 by the reprex package (v0.3.0)

Appreciate your help, and continued learning!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.