创建一个R循环以从表写入CSV文件

我在R studio中有很多表,分别是“ zero.cells”,“ one.cells”(依此类推),直到“ fifteen.cells”。

我想使用write.csv2,例如write.csv2(zero.cells,file = "zero.cells.csv")

在csv中写入所有这些表

是否可以使用一个循环来完成此任务,而不必为每个文件都将其全部写出? 谢谢!

wx0806 回答:创建一个R循环以从表写入CSV文件

我猜Rstudio中对象的名称都以.cells为名?和其他具有该名称部分的对象不存在吗? 然后,以下方法将起作用:

dataframe_names=ls(pattern="\\.cells") #find all the objects in your environment with ".cells" in their name. 
#I suggest checking this by printing the content of dataframe_names to the console:
dataframe_names

# if these are all correct run the following

for(dfn in dataframe_names){
    write.csv2(get(dfn),file=paste(dfn,".csv")
}
,

我与@TobiO有所不同,也许会更困难。

我从这里使用了一个函数:link

numbers2words <- function(x){
  ## Function by John Fox found here: 
  ## http://tolstoy.newcastle.edu.au/R/help/05/04/2715.html
  ## Tweaks by AJH to add commas and "and"
  helper <- function(x){

    digits <- rev(strsplit(as.character(x),"")[[1]])
    nDigits <- length(digits)
    if (nDigits == 1) as.vector(ones[digits])
    else if (nDigits == 2)
      if (x <= 19) as.vector(teens[digits[1]])
    else trim(paste(tens[digits[2]],Recall(as.numeric(digits[1]))))
    else if (nDigits == 3) trim(paste(ones[digits[3]],"hundred and",Recall(makeNumber(digits[2:1]))))
    else {
      nSuffix <- ((nDigits + 2) %/% 3) - 1
      if (nSuffix > length(suffixes)) stop(paste(x,"is too large!"))
      trim(paste(Recall(makeNumber(digits[
        nDigits:(3*nSuffix + 1)])),suffixes[nSuffix],",Recall(makeNumber(digits[(3*nSuffix):1]))))
    }
  }
  trim <- function(text){
    #Tidy leading/trailing whitespace,space before comma
    text=gsub("^\ ","",gsub("\ *$",gsub("\,text)))
    #Clear any trailing " and"
    text=gsub(" and$",text)
    #Clear any trailing comma
    gsub("\ *,$",text)
  }  
  makeNumber <- function(...) as.numeric(paste(...,collapse=""))     
  #Disable scientific notation
  opts <- options(scipen=100) 
  on.exit(options(opts)) 
  ones <- c("","one","two","three","four","five","six","seven","eight","nine") 
  names(ones) <- 0:9 
  teens <- c("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen"," seventeen","eighteen","nineteen")
  names(teens) <- 0:9 
  tens <- c("twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety") 
  names(tens) <- 2:9 
  x <- round(x)
  suffixes <- c("thousand","million","billion","trillion")     
  if (length(x) > 1) return(trim(sapply(x,helper)))
  helper(x)
}


list_names<-gsub(" ",".",paste0(numbers2words(1:50),".cells"))

my_final_df<-data.frame()
for (name in list_names){
  my_final_df<-rbind(my_final_df,get(name))

}

write.csv2(my_final_df,"yourfile.csv")
本文链接:https://www.f2er.com/3116282.html

大家都在问