user195366
user195366

Reputation: 465

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

Upvotes: 3

Views: 444

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388807

Using base R, we can create a list of dataframes and merge them together using Reduce. For each list we check if the value is present in the new merged dataframe (df_merge) and assign values "Yes", "No" based on their presence/absence.

list_name <- mget(c("A", "B", "C"))

df_merge <- Reduce(function(x, y) merge(x, y, all = TRUE), list_name)
df_merge[names(list_name)] <- lapply(list_name, function(x) 
                              c("No", "Yes")[(df_merge$Name %in% x$Name + 1)])


df_merge

#  Name Code   A   B   C
#1  AAA  123 Yes Yes  No
#2  BBB  456 Yes  No Yes
#3  CCC  789 Yes  No  No
#4  AAB  124  No Yes  No
#5  AAC  125  No Yes  No
#6  BBA  457  No  No Yes
#7  BBC  458  No  No Yes

Upvotes: 0

zx8754
zx8754

Reputation: 56004

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

Upvotes: 1

Related Questions