'fill up a matrix with values based on common elements in data frames stored in list
I have a matrix with rows equal to the rows of a data frame (df) and columns equal to names of data frames stored in a list (list_ALL)
df:
COUNTRY
USA
Japan
Germany
Canada
Italy
Russia
listA:
COUNTRY
Italy
Russia
listB
COUNTRY
Japan
Canada
Italy
listALL<-list(listA,listB)
mat<-matrix(nrow = nrow(df),ncol = length(list_ALL))
colnames(mat)<-names(list_ALL)
rownames(mat)<-df$COUNTRY
I would like to fill up the matrix with 1 if a value in df is found in the list and with 0 if absent:
Output
mat
listA listB
USA 0 0
Japan 0. 1
Germany. 0. 0
Canada. 0. 1
Italy. 1. 1
Russia. 1. 0
Tried this:
for (i in seq_along(list_ALL)){
apply(mat, 2, function(x) ifelse(df$COUNTRY %in% list_ALL[[i]]$COUNTRY,1,0))}
However, it does not seem to fill up values
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
