Sample Rate in R

This may seem like a very simple R question, but I would appreciate an answer. I have a data frame in the form:

col1 col2 ag ah ag bi bg bh ci 

I want to convert it to counts, so the result will be like this. I tried using the table () function, but apparently I can get a counter for one column.

  abc g 2 1 0 h 1 1 0 i 0 1 1 

How do I do this in R?

+6
source share
2 answers

I'm not quite sure what you used, but table works great for me!

Here's a minimal reproducible example:

 df <- structure(list(V1 = c("a", "a", "a", "b", "b", "b", "c"), V2 = c("g", "h", "g", "i", "g", "h", "i")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, -7L)) table(df) # V2 # V1 ghi # a 2 1 0 # b 1 1 1 # c 0 0 1 

Notes:

  • Try table(df[c(2, 1)]) (or table(df$V2, df$V1) ) to exchange rows and columns.
  • Use as.data.frame.matrix(table(df)) to get data.frame as output. ( as.data.frame will create a long data.frame , not the one you need in the same format).
+8
source

Using f from @Ananda you can use dcast

 library(reshape2) > dcast(f, V1~V2) Using V2 as value column: use value.var to override. Aggregation function missing: defaulting to length V1 ghi 1 a 2 1 0 2 b 1 1 1 3 c 0 0 1 

However, I only write this if you might need something more than just table (which for this case is the easiest right answer) in the future, for example:

 set.seed(1) f$var <- rnorm(7) > f V1 V2 var 1 ag -0.6264538 2 ah 0.1836433 3 ag -0.8356286 4 bi 1.5952808 5 bg 0.3295078 6 bh -0.8204684 7 ci 0.4874291 > dcast(f, V1~V2, value.var="var", fun.aggregate=sum) V1 ghi 1 a -1.4620824 0.1836433 0.0000000 2 b 0.3295078 -0.8204684 1.5952808 3 c 0.0000000 0.0000000 0.4874291 
+4
source

Source: https://habr.com/ru/post/954166/


All Articles