0

I have a .nc file which contains time series data of 2010-2020 for a region. I want to export the time series in a .csv format. I am using following code in R to do the same. I am able to print the output. Could anyone please help me how can I export the output in csv.

library(ncdf4)
library(tidyverse)

setwd("D:/Test/")

our_nc_data <- nc_open("D:/Test/Data.nc")
print(our_nc_data)
attributes(our_nc_data$var)
attributes(our_nc_data$dim)

mnth <- ncvar_get(our_nc_data, "datamonth") #'datamonth' is the desired variable
nmnth <- dim(mnth)

data <- ncvar_get(our_nc_data, "Al")  #'Al' is the desired variable
ndata <- dim(data)

print(c(mnth, data))  

The last line gives the output but as follows (a sample)

[1] 200601.00000 200602.00000 200603.00000 200604.00000 200605.00000 200606.00000 200607.00000 
200608.00000 200609.00000 200610.00000 200611.00000
[12] 200612.00000 200701.00000 200702.00000 200703.00000 200704.00000 200705.00000 
200706.00000 200707.00000 200708.00000 200709.00000 200710.00000
[23] 200711.00000 200712.00000 200801.00000 200802.00000 200803.00000 200804.00000 14.08254     
14.43839     14.57681     14.16317     15.02839     15.78833     15.37064
[34]     15.40193     14.82367     13.48399     15.12717     29.69734     40.03585     
35.27866     14.13794     14.27229     15.02839     15.78833

My desired output is a csv file in following format

mnth  data
200601  14.08254
200602  14.43839
200603  14.57681

How can I obtain this in R? Kindly help.

1 Answers1

0

try write.csv(var_name, "file_name.csv")

RYann
  • 567
  • 1
  • 7
  • I tried it but it can export only one variable at one time. I want to export both variables together in same csv file. – Alexia k Boston Jul 04 '23 at 18:30
  • combine them into a single data frame in R `bind_cols(mnth, data)` and then write the csv. you can use `bind_cols()` by installing the `tidyverse` packages or use base R with `cbind()` – RYann Jul 04 '23 at 21:38