Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

r - How could I set a year from a string with full date format?

This might sound like the most basic question but I rather going ahead with it!

-This is a section of a Shiny App-

I read a CSV file, one of it's column stoped being General as I'm used to see them but Date type and I only care about the year of that full date. It isn't always in the same way, meaning sometimes it's 10/24/1995 (month/day/year) and others it's 24/10/1995 (day/month/year). I was using the lubridate package to go with below simple lines

df$File.Date <- mdy(df$File.Date)
df$year  <- lubridate::year(df$File.Date)

But ever since it started displaying this Date format for this particular string it keeps on saying below error

Listening on http://127.0.0.1:6970
Warning: All formats failed to parse. No formats found.
Warning: Error in as.POSIXlt.character: character string is not in a standard unambiguous format
  152: stop
  151: as.POSIXlt.character
  149: year.default
  147: eventReactiveHandler [C:UsersMelania CBDocumentsMy timeShiny appModeling app/server.R#121]
  103: df
  102: exprFunc [C:UsersMelania CBDocumentsMy timeShiny appModeling app/server.R#132]
  101: widgetFunc
  100: func
   87: origRenderFunc
   86: renderFunc
   82: origRenderFunc
   81: output$new_date
    1: runApp

Sometimes I'm able to use Text to Columns in Excel and do it before using the App so I don't have to change df$File.Date but it started doing something weird that when I change it to General type it changes 10/31/2014 to 41943 and I simply get NOTHING, could somebody please lead my way on this?

question from:https://stackoverflow.com/questions/65907600/how-could-i-set-a-year-from-a-string-with-full-date-format

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Based on the point you only care about the year, here I a reproducible example with solution:

x1 <-format(seq(today()-10,today()-5,by='day'),'%m/%d/%Y')
x2 <- format(seq(today()-4,today(),by='day'), '%d/%m/%Y')
df <- data.frame(x=c(x1,x2))

df %>% separate(x,c('d1','d2','year')) %>% head()

   dm md year
1  01 16 2021
2  01 17 2021
3  01 18 2021
4  01 19 2021

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...