Showing posts with label factor. Show all posts
Showing posts with label factor. Show all posts

Sunday, December 17, 2017

How do you draw a bar graph from a table of X,Y values?

In a previous post you saw how to create a data frame in R using a set off x and y values as shown:

  x      ItmVal
1 A     69
2 B     47
3 C     11
4 D     12
5 E     42
6 F     24


Here 1 to six are line numbers.

It is easy to draw a bar graph using this data:
------
>  dap <- br="" data.frame="">+  x=factor(c("A","B","C","D","E","F"), levels=c("A","B","C","D","E","F")),
+ ItmVal=c(69,47,11,12,42,24)
+ )
-----------
You map the data to aesthetics as shown and you can display your graph as shown.


ggplot-bargraph1

On the other hand if you want a different color for each of the different x values you could use this:


ggplot_bargraph2

Thursday, December 14, 2017

How do you use factor/s in R Programming?

Factors are variables to represent categories. Categories are discrete and not continuous. In statistics there is a need for such a variable.

Let us say, I roll the dice a dozen times and come up with values for each roll as shown:
2,4,5,3,2,6,10,5, 9,6,4,5

I can gather these in a data as shown in R with "dat":
data
---------------------------------






---------------------------------
Now I use 'factor' as used in R:
facData=factor(data)
--------------------

-----------------------
factor just took one unique item from the list presented to it to display in Levels. There were two 4's, three 5's and two 6's. It categorized them.

While the original data was numeric they could be also character data in "datac" below:


-------------------------------
We know the unique ones in the above data. How are we going to find how many of each are there?
For this we can use the table() in R as shown below:
------------------------------------

You can check for yourself, that it picked the correct value for each category.