0

I'm pretty new in R. Currently trying to write a function that takes a path, a variable name and a variable label, and turn it into a plot.

Code:

plot_var <- function(dirpath,parname,parnamequotes) {
  mydata <- read.csv(dirpath, skip=6)
  par(mfrow=c(1,2))
  plot(mydata$parname, mydata$trust_coop_total, xlab = parnamequotes, ylab = "trust_coop", main = "Sensitivity of max_trust", pch=16, col = rgb(0,191,255,50, maxColorValue = 255))
  }
plot_var("XXXX.csv", max_trust, "max_trust")

I keep getting this error: Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

However, I believe that the independent and dependent variables are the same length. What am I doing wrong?

rafaelc
  • 57,686
  • 15
  • 58
  • 82
maria118code
  • 153
  • 1
  • 14

1 Answers1

1

You should use

  • mydata[, parnamequotes] (return a vector) or,
  • mydata[[parnamequotes]] (return a vector) or,
  • mydata[parnamequotes] (return a data frame)

in place of mydata$parname (see this question) and remove parname from the function.

plot_var <- function(dirpath,parnamequotes) {
  mydata <- read.csv(dirpath, skip=6)
  par(mfrow=c(1,2))
  plot(mydata[, parnamequotes], 
       mydata$trust_coop_total, 
       xlab = parnamequotes, ylab = "trust_coop", 
       main = "Sensitivity of max_trust", 
       pch=16, col = rgb(0,191,255,50, maxColorValue = 255))
  }

plot_var("XXXX.csv", "max_trust")
DJack
  • 4,850
  • 3
  • 21
  • 45
  • great, thanks! Beginners question: when to use $ and when [,] ? – maria118code Apr 17 '18 at 11:01
  • You are welcome. You cannot use $ with variable. See this question: https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-vector-of-column-names – DJack Apr 17 '18 at 11:07