How can I neatly clean my R workspace while preserving certain objects?

前端 未结 3 1553
面向向阳花
面向向阳花 2020-12-08 23:45

Suppose I\'m messing about with some data by binding vectors together, as I\'m wont to do on a lazy sunday afternoon.

    x <- rnorm(25, mean = 65, sd = 1         


        
3条回答
  •  情深已故
    2020-12-09 00:17

    Since I forgot that comments don't support full formatting, I wanted to respond to Hadley's recommendation here. Some of my existing code--perhaps sloppily--tends to work like this:

        caseid <- 1:25
        height <- rnorm(25, mean = 150, sd = 15)
        hd     <- data.frame(caseid, height)
        hd     <- hd [-(7), ] # Removing a case
        library(ggplot2)
        qplot(x = caseid, y = height, data = hd) # Plots 25 points
    

    In the above code, qplot() will plot 25 points, and I think it's because my global variables caseid and height are masking its attempt to access them locally from the provided dataframe. So, the case that I removed still seems to get plotted, because it appears in the global variables, though not the dataframe hd at the time of the qplot() call.

    My sense is that this behavior is entirely expected, and that the answer here is that I'm following a suboptimal coding practice. So, how can I start writing code that avoids these kinds of inadvertent collisions?

提交回复
热议问题