2015-07-20 99 views
0

循環,我有我的桌面上3個CSV文件名爲letter_xyx通過將下列數據幀到CSV文件創建 文件夾中通過目錄與功能R中

a <- data.frame(matrix(rnorm(20), nrow=10)) 
b <- data.frame(matrix(rnorm(20), nrow=10)) 
c <- data.frame(matrix(rnorm(20), nrow=10)) 

我創建了一個簡單的函數調用MULT那隻需使用第一列的總和在數據框中創建一個新列。

mult <- function(df){ 
df %>% mutate(sum(X1)) 
} 

我想編寫一個for循環,通過文件夾letter_xyz推移,執行該文件夾中的每個文件的功能,並在一個新的文件夾中返回每個文件作爲一個新的CSV文件。

我不太清楚該怎麼做, 謝謝!

回答

1

使用簡單for環和文件IO的功能,

## Your function 
mult <- function(df) df %>% mutate(sum(X1)) 

dir.create("output")         # create output folder 
for (file in list.files("data", full.names = T)) {  # loop through files in "data" folder 
    dat <- mult(read.csv(file))      # read file and apply function 
    fname <- gsub(".*/([A-Za-z]+\\.csv)", "\\1", file) # make output filename 
    write.csv(dat, sprintf("output/%s", fname))  # write file 
}