【发布时间】:2022-01-08 10:52:36
【问题描述】:
我有一个数据集,其中人们的完整年龄为 R 中的字符串(例如,“10 年 8 个月 23 天),我需要将其转换为有意义的数字变量。我正在考虑将其转换为这个人有很多天(这很难,因为几个月有不同的天数)。所以最好的解决方案可能是创建一个双变量,将年龄显示为 10.6 或 10.8,一些数字变量包含 10 年 8 个月 5 天的信息大于 10 年 7 个月 12 天。
这是我当前变量的示例
library(tibble)
age <- tibble(complete_age =
c("10 years 8 months 23 days",
"9 years 11 months 7 days",
"11 years 3 months 1 day",
"8 years 6 months 12 days"))
age
# A tibble: 4 x 1
complete_age
<chr>
1 10 years 8 months 23 days
2 9 years 11 months 7 days
3 11 years 3 months 1 day
4 8 years 6 months 12 days
这是我希望看到的可能结果的示例(age_num 的近似值)
> age
# A tibble: 4 x 2
complete_age age_num
<chr> <dbl>
1 10 years 8 months 23 days 10.66
2 9 years 11 months 7 days 9.92
3 11 years 3 months 1 day 11.27
4 8 years 6 months 12 days 8.52
总之,我有一个包含“complete_age”列的数据集,我想创建列“age_num”。
如何在 R 中做到这一点?我很难尝试使用 stringr 和 lubridate 但也许这是要走的路?
【问题讨论】:
标签: r data-cleaning lubridate stringr data-wrangling