ggplot2 aes_string() fails to handle names starting with numbers or containing spaces

前端 未结 4 861
刺人心
刺人心 2020-12-15 08:32

If the column names of a data.frame are started with numbers, or have spaces, aes_string() fails to handle them:

foo=data.frame(\"1         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 09:03

    The original question asked how to modify a value of a variable so it is acceptable to ggplot() when the value is not know beforehand.

    Write a function that adds back-ticks to the beginning and end of the value of the variable:

    # ggName -> changes a string so it is enclosed in back-ticks.
    #   This can be used to make column names that have spaces (blanks)
    #   or non-letter characters acceptable to ggplot2.
    #   This version of the function is vectorized with sapply.
    ggname <- function(x) {
        if (class(x) != "character") {
            return(x)
        }
        y <- sapply(x, function(s) {
            if (!grepl("^`", s)) {
                s <- paste("`", s, sep="", collapse="")
            }
            if (!grepl("`$", s)) {
                s <- paste(s, "`", sep="", collapse="")
            }
        }
        )
        y 
    }
    

    Examples:

    ggname(12)
    

    [1] 12

    ggname("awk ward")
    

    "`awk ward`"

    l <- c("awk ward", "no way!")
    ggname(l)
    

    "`awk ward`" "`no way!`"

提交回复
热议问题