Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add the index of list to bind_rows?

Tags:

dataframe

r

dplyr

I have this data:

dat=list(structure(list(Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(65, 75)), row.names = c(NA, -2L), class = "data.frame"),NULL, structure(list( Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(81,4)), row.names = c(NA,-2L), class = "data.frame"))

I want to use combine using bind_rows(dat) but keeping the index number as a varaible Output Include Type([[1]] and [[3]])

  type   Group.1     Pr1
1   1      C          65
2   1      D         75
3   3      C         81
4   3      D          4
like image 828
temor Avatar asked Jun 13 '18 09:06

temor


1 Answers

According to the documentation of bind_rows() you can supply the name for .id argument of the function. When you apply bind_rows() to the list of data.frames the names of the list containing your data.frames are assigned to the identifier column. [EDIT] But there is a problem mentioned by @Wimpel:

names(dat)
NULL

However, supplying the names to the list will do the thing:

names(dat) <- 1:length(dat)
names(dat)
[1] "1" "2" "3"
bind_rows(dat, .id = "type")
  type Group.1 Pr1
1    1       C  65
2    1       D  75
3    3       C  81
4    3       D   4

Or in one line, if you prefer:

bind_rows(setNames(dat, seq_along(dat)), .id = "type")
like image 152
utubun Avatar answered Oct 07 '22 22:10

utubun