Conditional Merge in R Data Frame using a String as a search
I am prepping a database for plotting in ggplot
where I will plot a large geom_point()
plot. I would like one set of point to stand out and was thinking of making a dummy column so that I could use that column as a color variable as in:
p <- ggplot(data, aes(x-x,y-y,color=color)
colors=c("yes"="orange2", "no"="grey")
scale_color_manual(values=colors)
开发者_StackOverflow中文版
to make the dummy column I wanted to do as follows:
df$color <- "no"
to set the default color, and then use a grep substitute to make a highlight color.
df$color[grep("string", df$V1, ignore.case=T),] < "yes"
where V1
is a column that contains the string I would like to substitute. Although I would love some suggestions on how to get the substitution I would also be interested in learning about a more direct coloring method that would involve highlighting data of a particular value.
thanks
Here is one way to do it using grepl
. I am using the mtcars
data set for illustrative purposes. Say you want Merc
to stand out. You can call
ggplot(mtcars, aes(mpg, hp)) +
geom_point(aes(colour = grepl('Merc', rownames(mtcars)))) +
scale_colour_manual("Merc", values = c('black', 'red'))
精彩评论