Search code examples
rdataframenames

How can you create custom headers using Table function in R?


I have a data frame for each team that looks like nebraska below. However, some of these poor teams don't have a single win, so their $Outcome column has nothing but L in them.

> nebraska
           Teams     Away/Home   Score   Outcome
1     Arkansas State      Away    36 
2           Nebraska      Home    43        W
3           Nebraska      Away    35        L
4             Oregon      Home    42                          
5  Northern Illinois      Away    21                          
6           Nebraska      Home    17        L
7            Rutgers      Away    17                          
8           Nebraska      Home    27        W
9           Nebraska      Away    28        W
10          Illinois      Home     6                          
11         Wisconsin      Away    38                          
12          Nebraska      Home    17        L
13        Ohio State      Away    56                          
14          Nebraska      Home    14        L

When I run table(nebraska$Outcome it gives me my expected outcome:

table(nebraska$Outcome)
  L W 
7 4 3 

However, for the teams that don't have a single win (like Baylor), or only have wins, it only gives me something like:

table(baylor$Outcome)
  L
7 7 

I'd like to specify custom headers for the table function so that I can get have something like this output:

table(baylor$Outcome)
  L W
7 7 0

I've tried passing the argument dnn to the table function call, but it throws an error with the following code:

> table(baylor$Outcome,dnn = c("W","L",""))

Error in names(dn) <- dnn : 'names' attribute [3] must be the same length as the vector [1]

Can someone tell me how I can tabulate these wins and losses correctly?


Solution

  • Try this:

    with(rle(sort(nebraska$Outcome)),
         data.frame(W = max(0, lengths[values == "W"]),
                    L = max(0, lengths[values == "L"])))
    #  W L
    #1 3 4