Question

R PROGRAMMING QUESTION To try and get the frequency of variable within a column, I used...

R PROGRAMMING QUESTION

To try and get the frequency of variable within a column, I used the following code:

    s = table(student$Sport)
    t = as.data.frame(s)
    names(t)[1] = 'Sport'
    t

Although this works, it gives me a massive list that is not sorted, such as this:

    1            Football    20310
    2            Rugby    80302
    3            Tennis    5123
    4            Swimming    73132
    …            …                    …
    68           Basketball           90391

How would I go about sorting this table, so that the most frequent sport is at the top.

Also, is there a way to only display the top 5 options? Rather than all 68 different sports?

Any help would be appreciated!

Homework Answers

Answer #1

Yes of course!

I'll take an example of "cars" data from R and explain.

So cars looks like this:

cars
speed dist
1 4 2
2 4 10
3 7 4
4 7 22
5 8 16
6 9 10
7 10 18
8 10 26
9 10 34
10 11 17
11 11 28
12 12 14
13 12 20

Now suppose you want to order it by column 1: The command is very simple

new = cars[order(cars[,1]),] ## Increasing

new = cars[order(-cars[,1]),] ## decreasing

How does it works?

Here we chose a column and order it. It gives us a permutation in increasing order. Then cars[order,] structure rearranges rows at that permutation giving you an ordered data frame.

Now if you want to display 5 rows only:

type:

cars[1:5,]

if you want to display 1,3,6,14th rows,

x<- c(1,3,6,14)

cars[x,]

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT