【发布时间】:2018-08-25 16:39:00
【问题描述】:
我有一个数据框,其中有一个文本字段,用于记录一个人在城市中停留的时间。它的格式为y year(s) m month(s),其中y 和m 为数字。如果此人在城市居住不到一年,则该值将仅采用 m months 格式
我想将此列转换为两个单独的数字列,其中一个显示生活的年数,另一个显示生活的月份。
这是我的数据框示例:
df <- structure(list(Time.in.current.role = c("1 year 1 month", "11
months",
"3 years 11 months", "1 year 1 month", "8 months"), City =
c("Philadelphia",
"Seattle", "Washington D.C.", "Ashburn", "Cork, Ireland")), .Names =
c("Time.in.current.role",
"City"), row.names = c(NA, 5L), class = "data.frame")
我想要的数据框看起来像:
result <- structure(list(Year = c(1, 0, 3, 1, 0), Month = c(1, 11,
11,
1, 8), City = structure(c(3L, 4L, 5L, 1L, 2L), .Label = c("Ashburn",
"Cork, Ireland", "Philadelphia", "Seattle", "Washington D.C."
), class = "factor")), .Names = c("Year", "Month", "City"), row.names
= c(NA,
-5L), class = "data.frame")
我正在考虑使用 grep 来定位哪些行中包含子字符串“year”,哪些行中包含子字符串“month”。但在那之后,我在尝试获取与“年”或“月”适当关联的数字时遇到了麻烦。
* 编辑 *
在我原来的帖子中,我忘了说明可能只有y year(s) 的情况。这是新的原始数据框和所需的数据框:
df <- structure(list(Time.in.current.role = c("1 year 1 month", "11
months",
"3 years 11 months", "1 year 1 month", "8 months", "2 years"),
City = c("Philadelphia", "Seattle", "Washington D.C.", "Ashburn",
"Cork, Ireland", "Washington D.C.")), .Names =
c("Time.in.current.role",
"City"), row.names = c(1L, 2L, 3L, 4L, 5L, 18L), class =
"data.frame")
result <- structure(list(Year = c(1, 0, 3, 1, 0, 2), Month = c(1, 11,
11,
1, 8, 0), City = structure(c(3L, 4L, 5L, 1L, 2L, 5L), .Label =
c("Ashburn",
"Cork, Ireland", "Philadelphia", "Seattle", "Washington D.C."
), class = "factor")), .Names = c("Year", "Month", "City"), row.names
= c(NA,
-6L), class = "data.frame")
【问题讨论】:
标签: r regex substring delimiter