How to refer to a variable name with spaces?

后端 未结 3 1515
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 07:32

In ggplot2, how do I refer to a variable name with spaces?

Why do qplot() and ggplot() break when used on variable names with

3条回答
  •  有刺的猬
    2020-12-08 08:05

    Answer: because 'x' and 'y' are considered a length-one character vector, not a variable name. Here you discover why it is not smart to use variable names with spaces in R. Or any other programming language for that matter.

    To refer to variable names with spaces, you can use either hadleys solution

    a.matrix <- matrix(rep(1:10,3),ncol=3)
    colnames(a.matrix) <- c("a name","another name","a third name")
    
    qplot(`a name`, `another name`,data=as.data.frame(a.matrix)) # backticks!
    

    or the more formal

    qplot(get('a name'), get('another name'),data=as.data.frame(a.matrix))
    

    The latter can be used in constructs where you pass the name of a variable as a string in eg a loop construct :

    for (i in c("another name","a third name")){
        print(qplot(get(i),get("a name"),
          data=as.data.frame(a.matrix),xlab=i,ylab="a name"))
        Sys.sleep(5)
    }
    

    Still, the best solution is not to use variable names with spaces.

提交回复
热议问题