[R] Question about Factors

cls59 chuck at sharpsteen.net
Mon Sep 14 05:56:03 CEST 2009




Chris Li wrote:
> 
> Hi all,
> 
> I am new to R and I have got a question in regards to factors.
> 
> Say I have a simple dataset like the following:
> 
> Name   Time     Value
> a         1:00     1.25
> a         2:00     1.26
> b         1:00     1.29
> b         2:00     1.28
> c         1:00     1.21
> c         1:30     1.20
> c         2:00     1.23
> 
> I want to write a script that automatically plot value against time for a,
> b and c. Because I have got more than 1 datasets, therefore the name of
> the next dataset may consist d, e, h and g. So I will need a script that
> can detect the changes in Name automatically.
> 
> Thank you very much for your time.
> 
> Chris
> 


I'm assuming you want something like a separate scatter plot for each
"level" of Name-- i.e. for this example a plot of Value ~ Time for 'a', then
a new plot of Value ~ Time for 'b', ect.

One easy way to chop a data frame into a bunch of mini data frames based on
the value of a factor is the  by() function. For example, supposing your
data frame is named "data", the following might produce what you want:

by( data, data[[ 'Name' ]], function(slice){

  # Slice is now a smaller data frame which contains only the
  # values which share a row with a one of the factor levels in Name

  dev.new()

  plot( Value ~ Time, data = slice,
    main = paste('Scatter plot for', slice[[ 'Name' ]][1])
  )

})


Another way to easily create the same plots and visualize them all on one
page as a series of small multiples would be to use Hadley Wickham's ggplot2
package:

qplot( Value ~ Time, data = data ) + facet_wrap( ~ Name )


Hope some of this helps!

-Charlie

-----
Charlie Sharpsteen
Undergraduate
Environmental Resources Engineering
Humboldt State University
-- 
View this message in context: http://www.nabble.com/Question-about-Factors-tp25428665p25429985.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list