Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new data frame from list of data frames using lapply

I have a list of data frames. Each list contains two columns "Name"and "Code"

A

Name Code
AAA  123
BBB  456
CCC  789

B

   Name Code
   AAA  123
   AAB  124
   AAC  125

C

Name Code
BBB  456
BBA  457
BBC  458
  1. I would like to create a new data frame "NEW" that contains all unique names and codes, so that I get

    Name Code AAA 123 AAB 124 AAC 125 BBB 456 BBA 457 BBC 458 CCC 789

  2. After having "NEW", I would like to compare the list of data frames with "NEW" and say if each name is present in one list. I Want to add new columns (with the names of the data frames on the list) to the "NEW" data frame, and put Yes or no, in case is present.

So get this

Name Code  A     B     C
AAA  123   YES   YES   NO
AAB  124   NO    YES   NO
AAC  125   NO    YES   NO
BBB  456   YES   NO    YES
BBA  457   No    NO    YES
BBC  458   NO    NO    YES
CCC  789   YES   NO    NO

I would like to do with lapply, but I'm not sure how to do everything.

Can you help me

like image 520
user195366 Avatar asked Nov 20 '25 02:11

user195366


1 Answers

Bind rows with ID, then reshape from long-to-wide, using data.table:

# example data
myList <- list(A = data.frame(x = 1:3),
               B = data.frame(x = 2:4),
               C = data.frame(x = 4:6))

library(data.table)

dcast(rbindlist(myList, idcol = "ID"), x ~ ID)
#    x  A  B  C
# 1: 1  1 NA NA
# 2: 2  2  2 NA
# 3: 3  3  3 NA
# 4: 4 NA  4  4
# 5: 5 NA NA  5
# 6: 6 NA NA  6
like image 88
zx8754 Avatar answered Nov 21 '25 18:11

zx8754



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!