1

I have a list with two dataframes:

dat.list<- list(dat1=data.frame(col1=c(3,4,5),
                                col2=c(5,3,1),
                                col3=c(8,2,5),
                                col4=c(6,7,4)),
                dat2=data.frame(col1=c(2,1,3),
                                col2=c(6,9,2),
                                col3=c(4,2,1),
                                col4=c(9,5,6)))
dat.list
# $dat1
#   col1 col2 col3 col4
# 1    3    5    8    6
# 2    4    3    2    7
# 3    5    1    5    4

# $dat2
#   col1 col2 col3 col4
# 1    2    6    4    9
# 2    1    9    2    5
# 3    3    2    1    6

I am trying to stack the columns in both dataframes in the list, so that "col3" is below "col1" and "col4" is below "col2", as shown below:

# $dat1
#  newcol1 newcol2
# 1       3       5
# 2       4       3
# 3       5       1
# 4       8       6
# 5       2       7
# 6       5       4

# $dat2
#   newcol1 newcol2
# 1       2       6
# 2       1       9
# 3       3       2
# 4       4       9
# 5       2       5
# 6       1       6

I have tried to do this adapting the answer of this post to a lapply() function as shown below, but I get the error "Object of type 'closure' is not subsettable".

lapply(dat.list, function(x) transform(x, 
                                       data.frame(grupo1 = unlist(c(.[,"col1"], .[,"col3"])),
                                                   grupo2 = unlist(c(.[,"col2"], .[,"col4"])))))

I have also explored solutions using map() and pivot_longer() but haven't found a way. How can I get the desired output?

markus
  • 25,843
  • 5
  • 39
  • 58
cholo.trem
  • 314
  • 2
  • 9

1 Answers1

1

You can use lapply and rbind together with setNames as follows:

cols1 <- c("col1", "col2")
cols2 <- c("col3", "col4")

lapply(dat.list, function(x) rbind(x[, cols1], setnames(x[, cols2], cols1)))

Returns

#$dat1
#  col1 col2
#1    3    5
#2    4    3
#3    5    1
#4    8    6
#5    2    7
#6    5    4
#
#$dat2
#  col1 col2
#1    2    6
#2    1    9
#3    3    2
#4    4    9
#5    2    5
#6    1    6

Without setNames, we would see the following error from rbind:

Error in match.names(clabs, names(xi)) : names do not match previous names

So we need a 'Simple way to get rbind to ignore column names'.

markus
  • 25,843
  • 5
  • 39
  • 58