建立连年人物链
build a character chain with successive years
我有一个带有 startYear、endYear 的 table,我想创建一个维度 Year 作为“startYear,endYear”
dt<- data.table(
startYear=c("1994","1995","2013"),
endYear=c("1995","2000","2021"))
我想要下面的dt table
dt<- data.table(
startYear=c("1994","1995","2013"),
endYear=c("1995","2000","2021"),
Year = c("1994,1995","1995,1996,1997,1998,1999,2000","2013,2014,2015,2016,2017,2018,2019,2020,2021")
我试试
dt$Year<- paste(seq(from = dt$startYear,
to = dt$endYear, by = 1))
但我收到一条错误消息
Error in seq.default(from = test$startYear, to = test$endYear, by = 1) :
'from' must be of length 1
我不知道如何更改它才能正常工作。
谢谢
文字预期输出...
dt[, Year := mapply(function(a, b) paste(seq(a, b), collapse = ","), startYear, endYear) ]
# startYear endYear Year
# <char> <char> <char>
# 1: 1994 1995 1994,1995
# 2: 1995 2000 1995,1996,1997,1998,1999,2000
# 3: 2013 2021 2013,2014,2015,2016,2017,2018,2019,2...
但是如果您打算稍后在内部对数字进行任何操作(不仅仅是折叠的字符串),那么将 Year
作为列表列处理可能会很有用,可用于 [=13] =] 和 dplyr
本身,可能在 base R 中不那么美观,但它仍然可以在那里工作,同样,这取决于你的用例。
dt[, Year := Map(seq, startYear, endYear) ]
# startYear endYear Year
# <char> <char> <list>
# 1: 1994 1995 1994,1995
# 2: 1995 2000 1995,1996,1997,1998,1999,2000
# 3: 2013 2021 2013,2014,2015,2016,2017,2018,...
我有一个带有 startYear、endYear 的 table,我想创建一个维度 Year 作为“startYear,endYear”
dt<- data.table(
startYear=c("1994","1995","2013"),
endYear=c("1995","2000","2021"))
我想要下面的dt table
dt<- data.table(
startYear=c("1994","1995","2013"),
endYear=c("1995","2000","2021"),
Year = c("1994,1995","1995,1996,1997,1998,1999,2000","2013,2014,2015,2016,2017,2018,2019,2020,2021")
我试试
dt$Year<- paste(seq(from = dt$startYear,
to = dt$endYear, by = 1))
但我收到一条错误消息
Error in seq.default(from = test$startYear, to = test$endYear, by = 1) :
'from' must be of length 1
我不知道如何更改它才能正常工作。 谢谢
文字预期输出...
dt[, Year := mapply(function(a, b) paste(seq(a, b), collapse = ","), startYear, endYear) ]
# startYear endYear Year
# <char> <char> <char>
# 1: 1994 1995 1994,1995
# 2: 1995 2000 1995,1996,1997,1998,1999,2000
# 3: 2013 2021 2013,2014,2015,2016,2017,2018,2019,2...
但是如果您打算稍后在内部对数字进行任何操作(不仅仅是折叠的字符串),那么将 Year
作为列表列处理可能会很有用,可用于 [=13] =] 和 dplyr
本身,可能在 base R 中不那么美观,但它仍然可以在那里工作,同样,这取决于你的用例。
dt[, Year := Map(seq, startYear, endYear) ]
# startYear endYear Year
# <char> <char> <list>
# 1: 1994 1995 1994,1995
# 2: 1995 2000 1995,1996,1997,1998,1999,2000
# 3: 2013 2021 2013,2014,2015,2016,2017,2018,...