Getting strings recognized as variable names in R

后端 未结 6 1780
我在风中等你
我在风中等你 2020-11-28 18:39

Related: Strings as variable references in R
Possibly related: Concatenate expressions to subset a dataframe


I\'ve simplified the question per the comment

6条回答
  •  情歌与酒
    2020-11-28 19:06

    Subsetting the data and combining them back is unnecessary. So are loops since those operations are vectorized. From your previous edit, I'm guessing you are doing all of this to make bubble plots. If that is correct, perhaps the example below will help you. If this is way off, I can just delete the answer.

    library(ggplot2)
    # let's look at the included dataset named trees.
    # ?trees for a description
    data(trees)
    ggplot(trees,aes(Height,Volume)) + geom_point(aes(size=Girth))
    # Great, now how do we color the bubbles by groups?
    # For this example, I'll divide Volume into three groups: lo, med, high
    trees$set[trees$Volume<=22.7]="lo"
    trees$set[trees$Volume>22.7 & trees$Volume<=45.4]="med"
    trees$set[trees$Volume>45.4]="high"
    
    ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth))
    
    
    # Instead of just circles scaled by Girth, let's also change the symbol
    ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth,pch=set))
    
    # Now let's choose a specific symbol for each set. Full list of symbols at ?pch
    trees$symbol[trees$Volume<=22.7]=1
    trees$symbol[trees$Volume>22.7 & trees$Volume<=45.4]=2
    trees$symbol[trees$Volume>45.4]=3
    
    ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth,pch=symbol))
    

提交回复
热议问题