1. Learn
  2. /
  3. คอร์ส
  4. /
  5. 中級 R

Connected

แบบฝึกหัด

日付の作成とフォーマット

To create a Date object from a simple character string in R, you can use the as.Date() function. The character string has to obey a format that can be defined using a set of symbols (the examples correspond to 13 January, 1982):

  • %Y: 4-digit year (1982)
  • %y: 2-digit year (82)
  • %m: 2-digit month (01)
  • %d: 2-digit day of the month (13)
  • %A: weekday (Wednesday)
  • %a: abbreviated weekday (Wed)
  • %B: month (January)
  • %b: abbreviated month (Jan)

The following R commands will all create the same Date object for the 13th day in January of 1982:

as.Date("1982-01-13")
as.Date("Jan-13-82", format = "%b-%d-%y")
as.Date("13 January, 1982", format = "%d %B, %Y")

Notice that the first line here did not need a format argument, because by default R matches your character string to the formats "%Y-%m-%d" or "%Y/%m/%d".

In addition to creating dates, you can also convert dates to character strings that use a different date notation. For this, you use the format() function. Try the following lines of code:

today <- Sys.Date()
format(Sys.Date(), format = "%d %B, %Y")
format(Sys.Date(), format = "Today is a %A!")

คำแนะนำ

100 XP
  • 日付を表す3つの文字列があらかじめ用意されています。as.Date() を使ってそれぞれを日付に変換し、date1、date2、date3 に代入してください。date1 のコードはすでに記述されています。
  • format() を使って、日付から有用な情報を文字列として取り出しましょう。1つ目の日付からは曜日を、2つ目の日付からは日(月の中の日付)を、3つ目の日付からは月名の略称と4桁の年をスペース区切りで取り出してください。