0

It has been a while since I've used R, so apologies for this very simple question. I probably wouldn't be asking it if I knew the correct way to find the question with the right keywords on a search engine.

I have a really long data table with a few columns, two of which are the subject for this question. The data table looks something like:

Row|Q|Year
1  |1|1990
2  |3|1995
3  |3|1991
4  |2|1990
5  |1|1990
6  |1|1990
7  |1|1992
8  |2|1991
9  |1|1990
10 |1|1990
11 |4|1991
12 |1|1992
13 |2|1995
14 |1|1993
15 |1|1990
....etc

I want to make a table that counts all the the Year records for a given Q like below

Q|1990|1991|1992|1993|1994|1995
1|5   |2   |2   |1   |3   |2
2|6   |6   |2   |1   |4   |1
3|2   |1   |4   |5   |6   |1
4|4   |3   |1   |2   |7   |6
...etc.

Or a way to extract that information one by by one Q=1, Year=1990: 5

I don't want to do it with a fancy package or with for/while loops, if I remember correctly it should just be something really simple with the basic R package like

table(data$Q,data$Year)

or

count(data$Q[Q==1,], data$Year[Year==1990,])

Though obviously that doesn't work because the length of X is different than the length of Y

Again sorry, a really dumb basic R question

MrFlick
  • 195,160
  • 17
  • 277
  • 295
MapDeath
  • 65
  • 7
  • 1
    Why doesn't `table(data$Q,data$Year)` work for you? That should do what you want. – MrFlick Jul 25 '20 at 01:37
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Here your output doesn't seem to match the input. Avoid using `...` since we can't reproduce that. – MrFlick Jul 25 '20 at 01:38
  • MrFlick, I have no clue why it was throwing an error before but it worked now. You know how you can take your computer to a repairman then as soon as you walk in the door it starts working all of a sudden? Something you could help me with is how to export this table to excel/csv – MapDeath Jul 25 '20 at 01:47
  • You can convert to a stanard data.frame with `as.data.frame.matrix(table(data$Q, data$Year))` and then use `write.csv()` like any other data.frame in R. – MrFlick Jul 25 '20 at 01:51
  • Many thanks. And how to add a column at the end that sums all the values in each of the Year columns? – MapDeath Jul 25 '20 at 01:54
  • New questions should not be asked in comments. First search for solutions, if none is found, feel free to ask a new question. And make sure the problem is reproducible. – MrFlick Jul 25 '20 at 01:58

0 Answers0