rg4s
rg4s

Reputation: 897

How to unpack particular list elements into dataframes in R?

Have been researching this question on SO, and found only solutions for merging list elements into one large data frame. However, I am struggling with unpacking only those elements that meet certain condition.

df1 <- iris %>% filter(Sepal.Length > 2.5)
df2 <- mtcars %>% filter(qsec > 16)
not_neccessary <- head(diamonds, 10)
not_neccessary2 <- head(beaver1, 12)

data_lists <- list("#123 DATA" = df1, "CON" = not_neccessary2, "#432 DATA" = df2, "COM" = not_neccessary) 

My goal is to convert only those list elements that contain "DATA" in their name. I was thinking about writing a loop function within a lapply:

a <- lapply(data_lists, function(x){if (x == "#+[1-9]+_+DATA"){new_df <- as.data.frame(x)}})

It does not work. Also was trying to make a for loop:

for (i in list){
  if (i == "#+[1-9]+_+DATA"){
    df <- i
  }
}

It does not work neither.

Is there any effective function that will unpack my list into particular dataframes by certain condition? My R skills are very bad, especially in writing functions, although I am not really new to this language. Sorry about that.

Upvotes: 1

Views: 39

Answers (2)

akrun
akrun

Reputation: 887148

Using %like%

result <- data_lists[names(data_lists) %like% 'DATA']

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

Use grepl/grep to find lists that have 'DATA' in their name and subset the list.

result <- data_lists[grepl('DATA', names(data_lists))]
#With `grep`
#result <- data_lists[grep('DATA', names(data_lists))]

Upvotes: 1

Related Questions