【问题标题】:R: Append ascii data and save it as csvR:追加ascii数据并保存为csv
【发布时间】:2016-08-31 13:28:25
【问题描述】:

我有如下所示的代码,它是用 R 编写的。它打算做的是读取文件夹中的一些 ascii 文件,一旦读取它们,它会将其数据一个附加到另一个文件中,同时排除每个初始文件的最后三行。然后它打算将最终文件保存在 csv 中。 我面临的问题是我的文件夹中写入了“final.csv”,但文件是空的....有人会知道为什么吗? 在这里,您将找到两个 ascii 文件,我打算将其中的数据附加到另一个之下,同时不包括每个文件的标题。

curl -g -O http://goldsmr4.gesdisc.eosdis.nasa.gov/opendap/MERRA2/M2T1NXSLV.5.12.4/2015/05/MERRA2_400.tavg1_2d_slv_Nx.20150501.nc4.ascii?T10M[0:23][241:241][343:343],lat[241:241],time[0:23],lon[343:343] -O http://goldsmr4.gesdisc.eosdis.nasa.gov/opendap/MERRA2/M2T1NXSLV.5.12.4/2015/05/MERRA2_400.tavg1_2d_slv_Nx.20150502.nc4.ascii?T10M[0:23][241:241][343:343],lat[241:241],time[0:23],lon[343:343]

我正在使用 OS X El Capitan v 10.11.4。以及 RStudio v 0.99.451 和 R 3.2.4。

setwd("/path to folder where the ascii files are located")
table<-list.files("/path to folder where the ascii files are located", full.names = TRUE)
table
# To read all the .ascii inside the folder
f<-function(x){
  k<-1
  y<-data.frame(x[k])
  while(k<=length(x)){
  k<-k+1
  y<-data.frame(y,x[k])
}
return(y)
}
info_data<-f(table)
# To read the data of each ascii and exlude the values of the three lines of each ascii
h<-function(z){  
  s<-c()
  t<-1
  while(t<=length(z)-3){
    s<-c(s,z[t])
    s<-s+1
  }
  return(s)
}
# Append the data of each ascii, one below the other, in a single file and save it as csv
g<-function(y){
  z<-c()
  j<-1
  r<-length(y[1,])
  while(j<=r){
    z<-append(z,h(y[,j]))
    j<-j+1}
  return (z)    
}
final<-g(info_data)
write.csv(final, "final.csv", sep = ",")

【问题讨论】:

  • 您在文件中的阅读情况如何?我在您的代码中没有看到任何读取功能(可能是read.csv?)。

标签: r csv append ascii


【解决方案1】:

我看不懂你的代码,但看你的口头描述......

要做的是读取文件夹中的一些ascii文件,一旦读取它们 在单个文件中将其数据逐个附加在另一个文件中,同时排除 每个初始文件的最后三行。然后它打算保存 csv 中的最终文件。

...以下应该做到这一点:

filenames <- dir("some folder", full.names=TRUE)
readitall <- lapply(filenames, read.csv)
trimit <- lapply(readitall, function(x) x[1:(NROW(x)-3),])
combineit <- do.call(rbind, trimit)
write.csv(combineit, "some name.csv")

【讨论】:

  • 谢谢!它真的很有用。尽管我可能认为您错过了用括号括起来的“trimit”?此外,还有一件小事:rbind 沿行放置值(沿第 1 行的值第一个 ascii,沿第 2 行的值第二个 ascii 等)。但是我希望将值排序在一个列中,例如第 1 列中的第一个 ascii 值,第 1 列中的第一个 ascii 值,等等。我已将 rbind 替换为 cbind,但它的作用是将值排序为单独的列。我该怎么做?
  • 我想解决这个问题,对于“combineit”,我替换为:combine_it
  • 对,必须有一个右括号(现在添加)。我不确定其余的。 “在单列中排序的值”或“沿第 1 列的第一个 ascii 值”是什么意思?一个可重现的例子会很有用。或您期望结果的“ascii 艺术”表示。
  • 类似这样的东西:“ascii1”:1 2 3。“ascii2”:10 20 30。“some name.csv”:1 2 3 10 20 30。对不起,我想把所有东西都放在一个柱子。在Markdown帮助中说要在行尾加两个空格做换行,好像不影响。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2020-05-08
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多