R, storing the output of the table () in the data frame

I have the following data frame:

id<-c(1,2,3,4,1,1,2,3,4,4,2,2) period<-c("first","calib","valid","valid","calib","first","valid","valid","calib","first","calib","valid") df<-data.frame(id,period) 

enter

 table(df) 

leads to

 period id calib first valid 1 1 2 0 2 2 0 2 3 0 0 2 4 1 1 1 

however, if I save it as a 'df' data frame

  df<-data.frame(table(df)) 

format 'df' will be similar to

 id period Freq 1 1 calib 2 2 2 calib 1 3 3 calib 1 4 4 calib 0 5 1 first 1 6 2 first 2 7 3 first 0 8 4 first 0 9 1 valid 0 10 2 valid 0 11 3 valid 2 12 4 valid 3 

how can i avoid this and how to save the first output like it in a data frame?

more importantly, is there a way to get the same result using 'dcast'?

+6
source share
2 answers

Would that help?

 > data.frame(unclass(table(df))) calib first valid 1 1 2 0 2 2 0 2 3 0 0 2 4 1 1 1 
+14
source

Think a little bit. I changed the ids in the data.frame example so that your ids are not 1: 4 to prove that the ids are wrapped in a table and not a sequence of rows.

 id <- c(10,20,30,40,10,10,20,30,40,40,20,20) period <- c("first","calib","valid","valid","calib","first","valid","valid","calib","first","calib","valid") df <- data.frame(id,period) 

Create a new data.frame in one of two ways. rengis answer is suitable for two-chamber frame frames with the first identifier column. It will not work so well if your data frame has more than two columns or the columns are in a different order.

An alternative would be to specify the columns and column order for your table:

 df3 <- data.frame(unclass(table(df$id, df$period))) 

the id column is included in the new data.frame as row.names(df3) . To add it to a new column:

 df3$id <- row.names(df3) df3 calib first valid id 10 1 2 0 10 20 2 0 2 20 30 0 0 2 30 40 1 1 1 40 
+1
source

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


All Articles