library(data.table)
cat("Source Date: 01/01/2020\n", file = "dt.csv")
dt <- data.table(a = 1:5)
fwrite(dt, "dt.csv", append =TRUE)
The first line in the written file will be the column name. To avoid the conflict with the first line with the "Source Date: 01/01/2020\n" consider setting an attribute.
library(data.table)
cat("Source Date: 01/01/2020\n", file = "dt.csv")
dt <- data.table(a = 1:5)
fwrite(dt, "dt.csv", append =TRUE)
rewound <- fread("dt.csv")
str(rewound)
#> Classes 'data.table' and 'data.frame': 5 obs. of 1 variable:
#> $ Source Date: 01/01/2020: int 1 2 3 4 5
#> - attr(*, ".internal.selfref")=<externalptr>
rewound
#> Source Date: 01/01/2020
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5
cat("Source Date: 01/01/2020\n", file = "dt.csv")
dt <- data.table(a = 1:5)
fwrite(dt, "dt.csv", append =FALSE)
rewound <- fread("dt.csv")
str(rewound)
#> Classes 'data.table' and 'data.frame': 5 obs. of 1 variable:
#> $ a: int 1 2 3 4 5
#> - attr(*, ".internal.selfref")=<externalptr>
rewound
#> a
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5
dt
#> a
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5
attributes(dt) <- list(sourcedate = "01/01/2020")
dt
#> [[1]]
#> [1] 1 2 3 4 5
#>
#> attr(,"sourcedate")
#> [1] "01/01/2020"
I am sorry for misleading you, i want to use the data.table package to export csv file as it shows
The only way to do that is to give the first row of the dt the value ‘a’. When appending, whatever is in the first row of the file being appended to is going to be the column name. There can’t be two.
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.