Tobias
Tobias

Reputation: 11

How to plot values from atomic vectors (matrix) in R

I am having a problem plotting and accessing the following matrix I have created.

Here I have created a version everyone may follow w/o my data.

a<-rnorm(10,0,1)
b<-rnorm(10,2,1)


J<-matrix(0,10,2)
colnames(J)<-c("a","b")
J[,1]<-a
J[,2]<-b

And then wish to plot. but I get error messages I do not understand:

with(J,plot(a,b))

+Error in eval(substitute(expr), data, enclos = parent.frame()) : + numeric 'envir' arg not of length one

with

plot(J$a,J$b)

+plot(J$a,J$b) +Error in J$a: $ operator is invalid for atomic vectors

Does anyone have any idea?

Kind Regards from GER

Upvotes: 0

Views: 6097

Answers (4)

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

If you want to access the columns of a matrix by their names:

plot(J[ , colnames(J) %in% c("a", "b")])

Upvotes: 0

Henry
Henry

Reputation: 6784

plot(J[,1], J[,2])

and

with(as.data.frame(J), plot(a,b))

both work

Upvotes: 1

mnel
mnel

Reputation: 115435

In your case, were you have a 2 column matrix J

plot(J) 

will work as will

 plot(J[,'a'], J[,'b'])

The `$` operator is not defined for matrices, but is for lists or data.frames

with will not work with matrices because a matrix cannot be an environment or an enclosure

Upvotes: 1

tim riffe
tim riffe

Reputation: 5691

It would work if J were defined as a data.frame, with columns a and b:

a<-rnorm(10,0,1)
b<-rnorm(10,2,1)

J <- data.frame(a,b)
with(J,plot(a,b))

$ only works with list objects (including data.frame). If you stick with the matrix, then you grab from the columns using brackets with indices or names:

J <- cbind(a,b)
plot(J,[,1],J[,2])
plot(J[,"a"],J[,"b"])

Upvotes: 2

Related Questions