簡體   English   中英

使用 R 將多個數據幀導出到.csv 文件中

[英]Export multiple data frames into .csv files using R

我想通過循環將幾個數據幀作為單獨的 csv 文件導出到工作目錄,而不是寫出所有名稱

##Sample data frame

employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))
d30 <- data.frame(employee, salary, startdate)

##Creating a few of the same name for illustrative purposes
d39 <- data.frame(employee, salary, startdate)
d40 <- data.frame(employee, salary, startdate)

for (list in c(d30,d39)){
  write.csv(list, file="list.csv", row.names = FALSE)
}

顯然我錯了。 但我不知道該怎么做。

遍歷數據框名稱。 我們假設所有名稱都以 d 開頭並且長度為 3。如果不是,請修改模式,或者如果您知道它們,則直接設置nms 我們還會再次檢查名稱是否為數據框,但如果您確定沒有不是數據框且名稱與模式匹配的對象,則可以省略該檢查。

nms <- ls(pattern = "^d..$")
for(nm in nms) {
  X <- get(nm)
  if (is.data.frame(X)) {
    filename <- paste0(nm, ".csv")
    message("writing out ", filename)
    write.csv(X, file = filename, row.names = FALSE)
  }
}
i <- 1 dfs <- list(d30, d39) for (df in dfs){ filename <- paste0("list", " ", i, ".csv") write.csv(list, file=filename, row.names = FALSE) i <- i + 1 }

數據

employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

代碼:

# create a new environment
myenv <- new.env()
# create data frames inside the environment
myenv$d30 <- data.frame(employee, salary, startdate)
myenv$d40 <- data.frame(employee, salary, startdate)

# get data from environment and write to files.
for (list in mget(ls(envir = myenv), envir = myenv)){
  write.csv(list, file="list.csv", row.names = FALSE)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM