Add name of xlab for each column in a function

Viewed 176

In this function I want to add the colnames of the variable tested. I dont know how to code this. Appreciate advise! :)

set.seed(8)
score1 <- sample(1:100,6)
score2 <- sample(1:100,6)
score3 <- sample(1:100,6)
x <- sample(101:200,6)
df <- data.frame(score1, score2, score3, x)

test <- function(i){
  plot(df[,i], df[,4], xlab=colnames(df[,i]), ylab="x")
}
test(1)
test(2)
test(3)

Then I want to get:

enter image description here enter image description here

enter image description here

1 Answers

When you subset the column using the index there is no column name attached to it.

df[, 1]
#[1] 96 52 55 79 12 42

colnames(df[, 1])
#NULL

Hence, you get the default x-axis in the plot.

Subset the column names using the index.

test <- function(i){
   plot(df[,i], df[,4], xlab=colnames(df)[i], ylab="x")
 }

test(2)

enter image description here

Related