R: “Unary operator error” from multiline ggplot2 command

前端 未结 4 964
半阙折子戏
半阙折子戏 2020-12-29 02:31

I\'m using ggplot2 to do a boxplot comparison of two different species, as indicated by the third column shown below:

> library(reshape2)
> library(ggp         


        
相关标签:
4条回答
  • 2020-12-29 02:44

    It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.

    This works:

    ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
    geom_boxplot() 
    

    The does not:

    ggplot(combined.data, aes(x = region, y = expression, fill = species))
    + geom_boxplot() 
    
    *Error in + geom_boxplot():
    invalid argument to unary operator*
    

    You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.

    0 讨论(0)
  • 2020-12-29 02:48

    It looks like you might have inserted an extra + at the beginning of each line, which R is interpreting as a unary operator (like - interpreted as negation, rather than subtraction). I think what will work is

    ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
        geom_boxplot() +
        scale_fill_manual(values = c("yellow", "orange")) + 
        ggtitle("Expression comparisons for ACTB") + 
        theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))
    

    Perhaps you copy and pasted from the output of an R console? The console uses + at the start of the line when the input is incomplete.

    0 讨论(0)
  • 2020-12-29 02:51

    This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

    Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

    ggplot(...) + geom_whatever1(...) +
      geom_whatever2(...) +
      stat_whatever3(...) +
      geom_title(...) + scale_y_log10(...)
    

    Don't put the dangling '+' at the start of the line, since that tickles the error:

    Error in "+ geom_whatever2(...) invalid argument to unary operator"

    And obviously don't put dangling '+' at both end and start since that's a syntax error.

    So, learn a habit of being consistent: always put '+' at end-of-line.

    cf. answer to "Split code over multiple lines in an R script"

    0 讨论(0)
  • 2020-12-29 02:54

    Try to consolidate the syntax in a single line. this will clear the error

    0 讨论(0)
提交回复
热议问题