Loading

블로그채널

Search !

[R] Chap2 Ex2 Character, Factor, and Logical Variables in R


Chapter 2. Exercises 2. 
Character, Factor, and Logical Variables in R

[R] Chap2 Ex2 Character, Factor, and Logical Variables in R

Analyzing Baseball Data with R, Introduction to R, page 56



Suppose one records the outcomes of a batter in ten plate appearances: Single, Out, Out, Single, Double, Out, Walk, Out, Single

(a) Use the c function to collect these outcomes in a character vector outcomes

> outcomes = c("Single", "Out", "Out", "Single", "Double", "Out", "Walk", "Out", "Single")

(b) Use the table function to construct a frequency table of outcomes.

> table(outcomes)

outcomes

Double    Out Single   Walk 

     1      4      3      1 

(c) In tabulating these results, suppose one prefers the results to be ordered from least-successful to most-successful. Use the following code to convert the character vector outcomes to a factor variable f.outcomes. 

f.outcomes <- factor(outcomes, levels = c("Out", "Walk", "Single", "Double"))

Use the table function to tabulate the value in f.outcomes. How does the output differ from what you saw in part (b)?

> table (f.outcomes)

f.outcomes

   Out   Walk Single Double 

     4      1      3      1 

(d) Suppose you want to focus only on the walks in the plate appearances. Describe what is done in each of the following statements.

outcomes == "Walk"

[1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE

sum(outcomes == "Walk")

[1] 1