我使用
在全局环境导入中设置了一组数据名称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))
}
现在我想将文件名中的名称(abc.csv,qwe.csv,xyz.csv)分配为for循环中的数据帧,如下所示
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)
提前致谢
答案 0 :(得分:1)
我试图理解你的代码及其背后的想法。 我使用了列表方法和tidyverse / dplyr解决方案
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 collumn with the tot_sal
})
由于我不确定这是否是您想要检索的内容,如果您想要一些不同的内容,请随时发表评论。