2016-11-30 48 views
0

我有我的計算機上的文件夾中> 50個的.csv文件。這些文件都包含相同的列標題/格式。導入很多的.csv文件到一個數據幀,並添加列基於名稱

我有代碼導入所有的.csv文件,並適當地稱爲:

path <- "~/My folder Location/" 
files <- list.files(path=path, pattern="*.csv") 
for(file in files) 
{ 
    perpos <- which(strsplit(file, "")[[1]]==".") 
    assign(
    gsub(" ","",substr(file, 1, perpos-1)), 
    read.csv(paste(path,file,sep=""))) 
} 

我現在有一個名爲很多的.csv文件,我更喜歡在環境中。但是,現在,我想基礎上,data.frame名字的部分,每部分data.frame中創建兩個列,然後創建一個大的data.frame

例如,如果data.frames之一是:

LeftArm_Beatrice 

我希望包括:

LeftArm_Beatrice$BodyPart <- c("LeftArm") 
LeftArm_Beatrice$Name <- c("Beatrice") 

又如,如果data.frames之一是:

RightLeg_Sally 

我希望包括:

RightLeg_Sally$BodyPart <- c("RightLeg") 
RightLeg_Sally$Name <- c("Sally") 

然後我想將所有這些50+數據幀合併爲一個。如果這些步驟可以包含在我的導入代碼中,那就太棒了。

謝謝!

+0

構建語句作爲一個字符串,然後使用'的eval(語句)'其中stmt是你創建 – johnjps111

+0

字符串是否有任何理由,你需要把這些全球環境中的數據?將它們列入清單會更安全,更易於操作。 –

+0

沒有必要把它們都在全球環境中,我這樣做就是我發現的代碼,讓我拉他們所有的唯一理由。你有一個替代在列表中有他們?謝謝。 – user2716568

回答

1
可能這項工作

!實際上我需要更多關於數據和命名的說明。因此,讓我知道,如果您有任何疑問

path = "D:/pathname/" 
l = list.files(path, pattern = ".csv") 
# below func does importing and creation of new columns 
func <- function(i){ 
    df <- read.csv(paste0(path,l[i])) 
    names <- unlist(strsplit(l[i], "_")) 
    df["BodyPart"] <- names[1] 
    df["Name"] <- names[2] 
    return(df) 
} 
# l1 shall have each of the dataframes individually with new columns attached 
l1 = lapply(1:length(l), func) 
# here we combine all dataframes together 
l2 <- as.data.frame(l1) 
+0

這是否回答OP的問題?你介意以下鏈接http://stackoverflow.com/help/someone-answers –

+1

對不起,我已經失去作用的最近和無法響應。 – user2716568

相關問題