2
$\begingroup$

I have imported a datafile in R. It has different columns. There is one column that has the name of Operating System belonging to that row information. I wanted to get the percentage share of each unique OS (windows, linux, ios etc) from this column and plot it. I am very new to R and would like to know if there is any inbuilt way to do this in R.

$\endgroup$
  • 1
    $\begingroup$ Since you're new to R, I recommend checking out this post to find a good list of resources to help get you up and running doing some analysis. $\endgroup$ – Chase Nov 24 '10 at 15:23
  • $\begingroup$ @Chase thanks for the link, yah i need to really learn the language, this was just something I need to do quickly. $\endgroup$ – sfactor Nov 24 '10 at 15:35
2
$\begingroup$

It seems the barplot() will be your friend in that case, e.g.

x <- sample(c("Win","Linux","Mac"), 100, replace=TRUE)
barplot(table(x))

This will work for variables of type character or factor. Another option is to use Cleveland's dotplot, see dotchart() (or dotplot()in the lattice package).

Update

You could replace table(x) by table(x)/sum(table(x))*100 to express data as % rather than counts. I know there are more elegant solutions in additional packages, but I can't remember their names actually. The table() function will also work for two-way classification, and marginal totals can easily be computed in a similar way; e.g. apply(table(x, y), 1, sum) gives rows marginal frequencies.

$\endgroup$
  • $\begingroup$ hmm the table function is a useful one it seems, but it would be better if I could show the percentages of the share rather than the count of each OS. Is there a way to do that? $\endgroup$ – sfactor Nov 24 '10 at 14:44
  • $\begingroup$ @sfactor I've updated my response accordingly. $\endgroup$ – chl Nov 24 '10 at 15:05
  • 3
    $\begingroup$ You guys are after the function prop.table() which comes with base R, it's essentially a wrapper for what you've got above. With your example, you'd want something like prop.table(table(x)) $\endgroup$ – Chase Nov 24 '10 at 15:14
  • $\begingroup$ @Chase (+1) Huh, yes... That's it! I was thinking of even more complex ways with addmargins() or margin.table(). $\endgroup$ – chl Nov 24 '10 at 15:33
4
$\begingroup$

Simulating some data for a good start

x<-sample(c("Win","Linux","Mac"),721,replace=TRUE)

The good practice is to hold such categorical variables as factors; one can convert character vector to factor with factor function:

x<-factor(x)

Then, plot called on it will make a barplot with counts; to convert it into per-cents, you can use table that makes counts of each level:

t<-table(x); barplot(t/sum(t)*100,ylab="Per cent")
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.