[R] Date read correctly from CSV, then reformatted incorrectly by R
jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Sat Nov 20 18:41:16 CET 2021
a) R data frames are column oriented. Do not fight this.
b) Data frame header names are character type. Period. Do not fight this.
It sounds like you need to reshape your data after you read it in. Provide the first five lines of your CSV file (or a reasonable facsimile if your data are confidential) and someone (me if I get to it first) can help make it more adapted to R.
Also, make sure you configure your email software to send plain text... formatted email gets damaged to varying degrees by the automatic stripping of formatting performed by the mailing list. And periodically read the Posting Guide for other advice.
On November 20, 2021 9:08:39 AM PST, Philip Monk <prmonk using gmail.com> wrote:
>Simple but infuriating problem.
>Reading in CSV of data using :
># CSV file has column headers with date of scene capture in format
># check.names = FALSE averts R incorrectly processing dates due to '/'
>data <- read.csv("C:/R_data/Bungala (b2000) julian.csv", check.names =
># Converts data table from wide (many columns) to long (many rows) and
>creates the new object 'data_long'
># Column 1 is the 'Buffer' number (100-2000), Columns 2-25 contain monthly
>data covering 2 years (the header row being the date, and rows 2-21 being a
>value for each buffer).
># Column headers for columns 2:25 are mutated into a column called 'Date',
>values for each buffer and each date into the column 'LST'
>data_long <- data %>% pivot_longer(cols = 2:25, names_to = "Date",
>values_to = "LST")
># Instructs R to treat the 'Date' column data as a date
>data_long$Date <- as.Date(data_long$Date)
>Using str(data), I can see that R has correctly read the dates in the
>format %d/%m/%y (e.g. 15/12/2015) though has the data type as chr.
>Once changing the type to 'Date', however, the date is reconfigured. For
>instance, 15/01/2010 (15 January 2010), becomes 0015-01-20.
>I've tried ```data_long$Date <- as.Date(data_long$Date, format =
>"%d/%m.%y")```, and also ```tryformat c("%d/%m%y")```, but either the error
>persists or I get ```NA```.
>How do I make R change Date from 'chr' to 'date' without it going wrong?
>Suggestions/hints/solutions would be most welcome. :)
>Thanks for your time,
>Part-time PhD Student (Environmental Science)
>Lancaster University, UK.
>I asked a question a few weeks ago and put together the answer I needed
>from the responses but didn't know how to say thanks on this list. So,
>thanks Andrew Simmons, Bert Gunter, Jeff Newmiller and Daniel Nordlund!
> [[alternative HTML version deleted]]
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.
Sent from my phone. Please excuse my brevity.
More information about the R-help