Simple data.frame format

I just returned to R from a long break and I had some real problems remembering how to change the data. I know that what I want to do is easy, but for some reason I am dumb today and confused myself with the melt and changed shape. If anyone could quickly point me in the right direction, that would be highly appreciated.

I have a data frame as such:

person week year personA 6 1 personA 22 1 personA 41 1 personA 42 1 personA 1 2 personA 23 2 personB 8 2 personB 9 2 .... personN xy 

I want to ultimately calculate the number of events by year and by person: (so that I can draw a quick line graph for each person over the years)

eg.

 person year1 year2 personA 4 2 personB 0 2 

Thanks so much for reading.

+7
source share
3 answers

I would probably use the reshape2 package and the dcast function, as it handles both conversion and aggregation in one step:

 library(reshape2) > dcast(person ~ year, value.var = "year", data = dat) Aggregation function missing: defaulting to length person 1 2 1 personA 4 2 2 personB 0 2 
+8
source

In this case, you can just use tapply :

 > with(data, tapply(week, list(person=person, year=year), length)) year person 1 2 personA 4 2 personB NA 2 

The result is a matrix. This solution creates NA if there are empty cells.

+7
source

xtabs from the R base works fine for this problem:

 dat <- read.table(text="person week year personA 6 1 personA 22 1 personA 41 1 personA 42 1 personA 1 2 personA 23 2 personB 8 2 personB 9 2 ", header=TRUE) xtabs(~person+year, data=dat) #----------------- year person 1 2 personA 4 2 personB 0 2 

You can pass your output to matplot, as it returns a table / matrix object:

 matplot( xtabs(~person+year, data=dat)) 

The output x-axis in this small example may not be what you want, but with a lot of years, there may be a more satisfactory default marking. Or you can suppress the default xaxt = "n" labels on the x axis and use axis to label as you wish:

 matplot( xtabs(~person+year, data=dat), xaxt="n", type="b") 
+5
source

All Articles