rnorouzian
rnorouzian

Reputation: 7517

Names of variables repeated 2 or more times in a list of data.frames in R

Generally, in a list of data.frames (for example below), I was wondering how I could obtain the names of the variables that are repeated 2 or more times (in this example the names would be "AA", "BB", "CC") across the data.frames?

r <- list( data.frame( AA = c(2,2,1,1,NA, NA), BB = c(1,1,1,2,2,NA), CC = c(1:5, NA)),

        data.frame( AA = c(1,NA,3,1,NA,NA), BB = c(1,1,1,2,NA,NA)),

        data.frame( AA = c(1,NA,3,1,NA,NA), BB = c(1,1,1,2,2,NA), CC = c(0:4, NA)) )

Upvotes: 1

Views: 346

Answers (1)

Joris C.
Joris C.

Reputation: 6234

You could:

  1. unlist the list to get all column names as a single vector,
  2. check for the (unique) duplicate names in the vector using duplicated.
## get names
vec <- names(unlist(r, recursive = FALSE))

## return duplicates
unique(vec[duplicated(vec)])
#> [1] "AA" "BB" "CC"

Upvotes: 2

Related Questions