Search for data frames by names in R

Asked

Viewed 61 times

-1

Good morning, I would like to create a function that I can use a data frame with a name that is saved in an object. Example: I have the dataframes: df1, df2, df3 All with columns: x, y and z

df1
x y z
1 3 4
2 2 5
3 1 6

df2
x y z
1 3 4
2 2 5
3 1 6

df3
x y z
1 3 4
2 2 5
3 1 6

And in that I would have objects n1, N2 and N3 that would have only the names of objects df1, df2 and df3

n1="df1"
n2="df2"
n3="df3"

And what I would need is to take the n objects with the names of the dataframes and make them receive the dataframes with their names or use the n’s as the dataframes themselves.

Would that be possible? Thank you.

2 answers

0

dfs <- paste0("df", sprintf("%02d", 1:10))

## Você pode atribuir valores de objetos diretamente às strings
## de nomes que quiser com a função assign()
for(i in dfs){
  my_dfi <- mtcars[sample(1:nrow(mtcars), size = 5),]
  assign(i, my_dfi)
}

## Você pode acessar os objetos chamando pelas strings de nomes
## com a função get() a alguma forma de loop
lista_dfs <- c()
for(i in dfs){
  lista_dfs[[i]] <- get(i)
}

0

in which case you can include these data frames in a list and name it with the name you want, each index in the list will be a data frame.

df1 <- data.frame(x = c(1:3), y = c(3:1), z = c(4:6))
df2 <- data.frame(x = c(1:3), y = c(3:1), z = c(4:6))
df3 <- data.frame(x = c(1:3), y = c(3:1), z = c(4:6))

listaDataFrame <- list(df1,df2, df3)
names(listaDataFrame) = c('df1', 'df2', 'df3')
listaDataFrame['df1']

$df1
  x y z
1 1 3 4
2 2 2 5
3 3 1 6

Browser other questions tagged

You are not signed in. Login or sign up in order to post.