Creating plots for String type columns in R

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.

• 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. – Chase Nov 24 '10 at 15:23
• @Chase thanks for the link, yah i need to really learn the language, this was just something I need to do quickly. – sfactor Nov 24 '10 at 15:35

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.

• 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? – sfactor Nov 24 '10 at 14:44
• @sfactor I've updated my response accordingly. – chl Nov 24 '10 at 15:05
• 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)) – Chase Nov 24 '10 at 15:14
• @Chase (+1) Huh, yes... That's it! I was thinking of even more complex ways with addmargins() or margin.table(). – chl Nov 24 '10 at 15:33

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")