0
votes

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?

1
use dput()to provide us your data. Then it will be much easier to help. - FAMG

1 Answers

1
votes

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")