dondapati
dondapati

Reputation: 849

Select the same column names of two lists

I want to Select the same column names from the two separate lists and output will be a list Here example:

List 1

> list(p1=data.frame(x=1,y=2), p2=data.frame(x=3,y=4), p3=data.frame(x=1,y=3))
$p1
  x y
1 1 2

$p2
  x y
1 3 4

$p3
  x y
1 1 3

List 2

> list(p1=data.frame(x=11,y=12), p2=data.frame(x=13,y=14), p3=data.frame(x=11,y=13))
$p1
   x  y
1 11 12

$p2
   x  y
1 13 14

$p3
   x  y
1 11 13

Output Format:

> list(p1=data.frame(a=1,b=2,a1=11,b1=12), p2=data.frame(a=3,b=4,a1=13,b1=14), p3=data.frame(a=1,b=3,a1=11,b1=13))
$p1
  a b a1 b1
1 1 2 11 12

$p2
  a b a1 b1
1 3 4 13 14

$p3
  a b a1 b1
1 1 3 11 13

Here List 1 and List 2 are having the same data frame names i.e,p1,p2,p3 and similar column names i.e..,x,y

and finally i want to list with combine the side by side same names of data frames and column names

Here i am refer some reference but it is a nested list

May be rapply and cbind will solve the my problem but i am not sure how to succeed

Thank you.

Upvotes: 1

Views: 118

Answers (2)

www
www

Reputation: 39154

A solution. First, use bind_cols to bind the columns. And then change the header using set_names.

library(tidyverse)

map2(lst1, lst2, bind_cols) %>%
  map(set_names, nm = function(x){
    y <- sub("x", "a", x)
    z <- sub("y", "b", y)
    return(z)
  })
# $p1
#   a b a1 b1
# 1 1 2 11 12
# 
# $p2
#   a b a1 b1
# 1 3 4 13 14
# 
# $p3
#   a b a1 b1
# 1 1 3 11 13

DATA

lst1 <- list(p1=data.frame(x=1,y=2), p2=data.frame(x=3,y=4), p3=data.frame(x=1,y=3))
lst2 <- list(p1=data.frame(x=11,y=12), p2=data.frame(x=13,y=14), p3=data.frame(x=11,y=13))

Upvotes: 1

denis
denis

Reputation: 5673

You are looking for mapply with cbind:

A <- list(p1=data.frame(x=1,y=2), p2=data.frame(x=3,y=4), p3=data.frame(x=1,y=3))
B <- list(p1=data.frame(x=11,y=12), p2=data.frame(x=13,y=14), p3=data.frame(x=11,y=13))

mapply(cbind,A,B,SIMPLIFY = F)

$p1
  x y  x  y
1 1 2 11 12

$p2
  x y  x  y
1 3 4 13 14

$p3
  x y  x  y
1 1 3 11 13

Upvotes: 3

Related Questions