R:x和y长度因功能而异

时间:2018-04-13 13:52:27

标签: r function vector plot

我在R中很新。目前正在尝试编写一个带路径,变量名和变量标签的函数,并将其转换成图。

代码:

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

我一直收到这个错误: Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

但是,我认为独立变量和因变量的长度相同。我做错了什么?

1 个答案:

答案 0 :(得分:1)

你应该使用

  • mydata[, parnamequotes](返回向量)或
  • mydata[[parnamequotes]](返回向量)或
  • mydata[parnamequotes](返回数据框)

代替mydata$parname(请参阅此question)并从功能中删除parname

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