[英]How to call data frames from Global environment using list of names in values
我在全局環境中使用了一組數據名
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)
提前致謝
我試圖了解您的代碼及其背后的想法。
我使用了列表方法和 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 column with the tot_sal
})
由於我不確定這是否正是您想要檢索的內容,如果您想要一些不同的東西,請隨時發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.