Using paste in for loop for graph

I am having trouble using the paste function. I have 12 plots and I want to replace the title, x and y label for each plots by the column names of the x and y matrices.

for (i in 1:ncol(y)) {
scatter.smooth(
x[, 1],
y[, i],
main = paste(colnames(y[, i]) "vs" colnames(x[, 1])),
xlab = paste(colnames(x[, 1])),
ylab = paste(colnames(y[, i])))

This is the error:
atterns.R:33:33: unexpected string constant
32: y[, i],
33: main = paste(colnames(y[, i]) "vs"

Hi @Samirah,
Try fixing this:

main = paste(colnames(y[, i]), " vs ", colnames(x[, 1])), 

HTH

Thank you.
It runs but only vs appears as the title, no x and y label.
A reproducible example maybe:

X <-
  mtcars[, c("mpg",
             "cyl",
             "disp",
             "hp")]

x = data.matrix(X)

Y <-
  mtcars[, c("drat",
             "wt",
             "qsec",
             "vs", "am")]

y = data.matrix(X)

for (i in 1:ncol(y)) {
  scatter.smooth(
    x[, 1],
    y[, i],
    main = paste(colnames(y[, i]), "vs", colnames(x[, 1])),
    xlab = paste(colnames(x[, 1])),
    ylab = paste(colnames(y[, i]))
  )
}

I have check the codes line by line, the colnames returns null values.

The indexing was wrong; you need to index the vector of column names; try this:

for (i in 1:ncol(y)) {
  scatter.smooth(
    x[, 1],
    y[, i],
    main = paste(colnames(y)[i], "vs", colnames(x)[1]),
    xlab = paste(colnames(x)[1]),
    ylab = paste(colnames(y)[i])
  )
}

HTH

1 Like

It works now. Thank you a lot.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.