Reputation: 515
I have set of data fames in Global environment importing by using
setwd("D:/dir/")
filenames <- list.files(pattern=".*csv")
for(i in filenames){
filepath <- file.path(paste(i,sep=","))
assign(i, read.csv(filepath, sep = ",", header=TRUE))
}
now i want to assign names in filenames(which are abc.csv,qwe.csv,xyz.csv) as dataframes in for loop as shown below
funct = function(x)
{
for (i in substr(unique(x),1,3))
i <# create df name by assign 1st dataframe name from filenames# > = i <from global environment>
male<-i[which(i$Level == "male"),]
male$tot_sal = male$sal+male$bonus
assign('male',male,envir=parent.frame()) #repeat loop for all 3 filename
}
funct(filenames)
Thanks in advance
Upvotes: 0
Views: 863
Reputation: 725
I tried to understand your code and the idea behind it.
I used a list approach and a tidyverse/dplyr solution
library(tidyverse)
setwd("D:/dir/")
filenames <- list.files(pattern=".*csv")
# read your files but store them in a list, where the key is the filename
my_files <- list()
for(i in filenames){
filepath <- file.path(paste(i,sep=","))
my_files[[i]]<- read.csv(filepath, sep = ",", header=TRUE)
}
# iterate over each file/df, filter for male and calculate the total
my_male_tot_list <- lapply(my_files, function(x){
x %>%
filter(Level == 'male') %>% # first filter for only males (i guess that is what you want to do)
mutate(tot_sal = sal+bonus) # create a new column with the tot_sal
})
Since I am not sure if this is exactly what you want to retrieve, please feel free to comment if you want something a little bit different.
Upvotes: 1