【问题标题】:How to compute summary statistics for age from the following data如何从以下数据计算年龄的汇总统计
【发布时间】:2017-09-23 23:06:23
【问题描述】:

我有以下数据。想要将“年”列中的数据转换为现在的年龄(以年计)。

tripduration    starttime   stoptime       Year
340         1/7/2017 0:00   1/7/2017 0:05  1994
439         1/7/2017 0:02   1/7/2017 0:09  1980
186         1/7/2017 0:04   1/7/2017 0:07  1984
442         1/7/2017 0:05   1/7/2017 0:13  1969
170        1/7/2017 0:07    1/7/2017 0:10  1986

因此,为了获得第一行的解决方案,我尝试从 1994 年减去开始时间 1/7/2017。但找不到差异。

您能否告诉我是否可以从给定的数据中找到以年为单位的年龄。我该怎么做才能从最后一个(年)列中找到年龄。

【问题讨论】:

  • 开始时间是 m/d/yyyy 格式还是 d/m/yyyy ?
  • 我意识到这并不重要,因为您只对年份感兴趣。根据下面的答案,我假设 d/m/yyyy。

标签: r


【解决方案1】:

是的,这是可能的。您只需将开始时间转换为一年,然后您就可以创建一个新列。然后你应该能够减去两年列。试试这个开始:

df <- data.frame(starttime=c("1/7/2017 0:00"))
df
#>       starttime
#> 1 1/7/2017 0:00
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
year(strptime(df$starttime, "%d/%m/%Y"))
#> Warning in strptime(df$starttime, "%d/%m/%Y"): unknown timezone 'default/
#> America/Vancouver'
#> [1] 2017

还有一个基本的 R 解决方案(无需加载 lubridate 包):

df <- data.frame(starttime=c("1/7/2017 0:00"))
df
#>       starttime
#> 1 1/7/2017 0:00
strptime(df$starttime, "%d/%m/%Y")$year + 1900
#> [1] 2017

【讨论】:

  • 感谢您提供详细信息。不使用库包lubridate是否可以得到结果
【解决方案2】:

我们可以使用正则表达式来识别年份。

# Create example data frame
dt <- read.table(text = "tripduration    starttime   stoptime       Year
340         '1/7/2017 0:00'   '1/7/2017 0:05'  1994
                439         '1/7/2017 0:02'   '1/7/2017 0:09'  1980
                186         '1/7/2017 0:04'   '1/7/2017 0:07'  1984
                442         '1/7/2017 0:05'   '1/7/2017 0:13'  1969
                170        '1/7/2017 0:07'    '1/7/2017 0:10'  1986",
                header = TRUE, stringsAsFactors = FALSE)

# Use regular expression to get the year in starttime
dt$startYear <- as.numeric(gsub(".*(\\d{4}).*", "\\1", dt$starttime))
# Calculate the age
dt$age <- dt$startYear - dt$Year
dt
  tripduration     starttime      stoptime Year startYear age
1          340 1/7/2017 0:00 1/7/2017 0:05 1994      2017  23
2          439 1/7/2017 0:02 1/7/2017 0:09 1980      2017  37
3          186 1/7/2017 0:04 1/7/2017 0:07 1984      2017  33
4          442 1/7/2017 0:05 1/7/2017 0:13 1969      2017  48
5          170 1/7/2017 0:07 1/7/2017 0:10 1986      2017  31

【讨论】:

  • 我有一些空值作为我的“年份”列。我正在尝试使用 if (is.integer(df$Year)) { $dt$age
  • 使用 ifelse。不要使用 if。
猜你喜欢
  • 2019-08-18
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2011-05-26
相关资源
最近更新 更多