How to avoid columns getting renamed when subsetting dataframes from a list?

I have a simple list of lists:

mydf1 <- data.frame("foo"=c(1,2,3),
                    "bar"=c(4,5,6))
mynum1 <- 5
mychar1 <- c("hello")

mylist1 <- list("mydf1"=mydf1,
                "mynum1"=mynum1,
                "mychar1"=mychar1)


mydf2 <- data.frame("foo"=c(1,2,3),
                    "bar"=c(4,5,6))
mynum2 <- 5
mychar2 <- c("hello")

mylist2 <- list("mydf2"=mydf2,
                "mynum2"=mynum2,
                "mychar2"=mychar2)

biglist <- list(mylist1, mylist2)

I want to return elements within the lists having class data.frame - so in this example I'd like to return only mydf1 and mydf2 exactly how they are in their respective list:

for(i in seq_along(biglist)){
  for(k in seq_along(i)){
    
    test_list <- list(biglist[[i]])
    
    
     print(as.data.frame(test_list[[k]][which(lapply(test_list[[k]], is.data.frame)==TRUE)]))
    
    
  }
}
  mydf1.foo mydf1.bar
1         1         4
2         2         5
3         3         6
  mydf2.foo mydf2.bar
1         1         4
2         2         5
3         3         6

The problem is that my column names are renamed, seemingly prepended with the respective "<original df name>.<original column name>"

I just want the original names, foo and bar

I think you overcomplicated it a bit with the nested for loop. This should already do the trick:

for(i in seq_along(biglist)){
  
  pos <- which(lapply(biglist[[i]], is.data.frame) == TRUE)
  
  print(biglist[[i]][[pos]])
  
}
#>   foo bar
#> 1   1   4
#> 2   2   5
#> 3   3   6
#>   foo bar
#> 1   1   4
#> 2   2   5
#> 3   3   6

Created on 2022-10-27 with reprex v2.0.2

Kind regards

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.