You can extract multiple columns at once from a dataframe by doing df_cleaned <- df[,c("price","date")]
. But for processing 50 different dataframes (all with the same column names), you can use a for
loop. Here is a way to do it:
1) define the list of dataframes to be proceed
list_of_df = list.files(pattern = ... , path = ...) # ... stands for argument you have to pass and dependent of your files. check the ?list.files
2) loop over the list of dataframes, clean them and assign them to your environment:
for(i in list_of_df)
{
df = read.table(i,...) # ... stands for arguments to be passed in this function and dependent of your type of file. Check ?read.table
df <- df[,c("price","date")]
assign(paste0(i,"_cleaned"), df,.GlobalEnv)
}
Advantages: you will have your 50 dataframe cleaned and ready to be used in your environment.
Inconvenients: You have 50 dataframes in your environment which can be messy
Alternative: As proposed by @thelatemail is to stored these 50 cleaned dataframes into a list. Like that you will have a single object in your environment filled with your dataframes. To do that, the procedure is about the same:
1) define the list of dataframes to be proceed
list_of_df = list.files(pattern = ... , path = ...) # ... stands for argument you have to pass and dependent of your files. check the ?list.files
2) Create a list object to stored dataframes
final_list = vector("list", length(list_of_df)
names(final_list) = list_of_df
3) loop over your list of dataframes, clean them and add them to the list object:
for(i in 1:length(list_of_df))
{
df = read.table(list_of_df[i],...) # ... stands for arguments to be passed in this function and dependent of your type of file. Check ?read.table
df <- df[,c("price","date")]
final_list[[i]] <- df
}