0
a<-c(1,2,3,4) 
b<-c(1,2,3,4) 
c<-c(2,3,4,5)
f<-c(5,6,7,8)
p<-c(3,7,6,5)
df = data.frame(a,b,c,f,p)

for (i in c('c','f','p'))
    plot(df$a, df$i)

I am trying to use a loop to plot some columns of a df but df$columnName does not appear to select the correct columns.

I have also tried plot(a~i, df) and it does not work also. Please help!

1
  • Do you need matplot('colnames<-'(t(df[-1]), df$a), type = 'l') Commented Nov 27, 2018 at 3:43

1 Answer 1

1

I don't think you can use the df$ style of indexing for some variable that holds a string. If you switch to square brackets for column indexing (making sure not to forget the empty row index to select all rows) then you can use a variable holding a column name.

The following works to make three plots of the variables in your vector:

par(mfrow=c(3,1))
for (i in c('c','f','p'))
    plot(df[,'a'], df[,i])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.