user3723264
user3723264

Reputation: 3

Error $ operator is invalid for atomic vectors in making histogram R

i'm trying to create a histogram in R.

Here are my data:

wealth<-c(100,150,200,240,300)
 age <- c(60,65,70,75,80)

I want the y axis to be wealth value and x axis be age

I have tried :-

hist(age$wealth,
 xlab="age",
 main="wealth") 

but it says "Error in age$wealth : $ operator is invalid for atomic vectors".

Any suggestions would be greatly appreciated! Many thanks in advance.

Upvotes: 0

Views: 9565

Answers (3)

jogall
jogall

Reputation: 671

As already said above, wealth and age are separate atomic vectors, and are thus independent from each other.

You might find it more useful to create a matrix or a dataframe to store your variables in, especially as the number of variables you have to work with increases. For instance:

> myDF <- data.frame(wealth = c(100,150,200,240,300), age = c(60,65,70,75,80))

Then you can use the $ operator to construct your barplot, like so:

> barplot(myDF$wealth, myDF$age, names.arg = myDF$age)

Upvotes: 2

Math
Math

Reputation: 2436

age$wealth means access the element wealth of the list age. Here age is an atomic vector (you created it with c()) so you cannot access the element wealth as it does not exist.

hist plots an histogram, i.e. a distribution, you probably want to use barplot to represent your data.

Upvotes: 1

Rich Scriven
Rich Scriven

Reputation: 99351

You can't use the $ operator because wealth and age are separate vectors. Also, a barplot might be better for this, unless you want a frequency or probability plot.

> barplot(wealth, names.arg = age)

enter image description here

Upvotes: 2

Related Questions