I have summarized a column of a data frame (call this DATA) that consists of IDs so I get the total number of each ID in the given column. I'd like to convert this to another data frame (call this TOTALNUM), so I have two columns. The first column is the ID itself and the second column is the total number of each ID. Is this possible?
Sample data:
ids <- c(1,2,3,4,5,1,2,3,1,5,1,4,2,2,2)
info <- c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C")
DATA <- data.frame(ids, info)
DATA$ids <- as.factor(DATA$ids)
What I would like to put in a data frame: Top row would be the first column in a new data frame. Second row would be the second column in a new data frame.
summary(DATA$ids)
This is what I would like the data frame to look like:
ids nums
1 4
2 5
3 2
4 2
5 2
Thanks!!
With your approach, you can take advantage of the fact that summary
returns a vector of counts, with names for each value of ids
:
> my.summary <- summary(DATA$ids)
> data.frame(ids=names(my.summary), nums=my.summary)
ids nums
1 1 4
2 2 5
3 3 2
4 4 2
5 5 2
Or--and this approach is more straightforward--you can create a frequency table based on ids
and then convert that to a data frame:
> as.data.frame(table(ids), responseName="nums")
ids nums
1 1 4
2 2 5
3 3 2
4 4 2
5 5 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With