【发布时间】:2018-02-18 18:23:56
【问题描述】:
我有这个数据表:
> str(merged.tables_t)
Classes ‘data.table’ and 'data.frame': 324326 obs. of 18 variables:
$ Store : int 2 2 2 2 2 2 2 2 2 2 ...
$ DayOfWeek : int 1 1 3 7 5 5 4 2 6 7 ...
$ Date : Factor w/ 942 levels "2013-01-01","2013-01-02",..: 903 315 366 832 298 214 395 491 908 384 ...
$ Sales : int 4123 4017 0 0 4524 4776 4214 5992 2404 0 ...
$ Customers : int 491 509 0 0 531 545 493 628 303 0 ...
$ Open : int 1 1 0 0 1 1 1 1 1 0 ...
$ Promo : int 0 0 0 0 1 1 0 1 0 0 ...
$ StateHoliday : Factor w/ 4 levels "0","a","b","c": 1 1 2 1 1 1 1 1 1 1 ...
$ SchoolHoliday : int 0 0 1 0 1 1 0 0 0 0 ...
$ StoreType : Factor w/ 4 levels "a","b","c","d": 1 1 1 1 1 1 1 1 1 1 ...
$ Assortment : Factor w/ 3 levels "a","b","c": 1 1 1 1 1 1 1 1 1 1 ...
$ CompetitionDistance : int 570 570 570 570 570 570 570 570 570 570 ...
$ CompetitionOpenSinceMonth: int 11 11 11 11 11 11 11 11 11 11 ...
$ CompetitionOpenSinceYear : int 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...
$ Promo2 : int 1 1 1 1 1 1 1 1 1 1 ...
$ Promo2SinceWeek : int 13 13 13 13 13 13 13 13 13 13 ...
$ Promo2SinceYear : int 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 ...
$ PromoInterval : Factor w/ 4 levels "","Feb,May,Aug,Nov",..: 3 3 3 3 3 3 3 3 3 3 ...
- attr(*, ".internal.selfref")=<externalptr>
我只需要创建一个新变量来合并两个列 CompetitionOpenSinceYear 和 CompetitionOpenSinceMonth。
首先,我创建一个名为 CompetitionDate 的新变量
merged.tables_t[,"CompetitionDate"]<-NA
然后,我修改这个变量的包含:
merged.tables_t[merged.tables_t[,19],as.character(as.Date(as.yearmon(with(merged.tables_t,sprintf("%d%02d",CompetitionOpenSinceYear,CompetitionOpenSinceMonth))))),]
它给了我这个错误:
[.data.table(merged.tables_t, , CompetitionDate = as.character(as.Date(as.yearmon(with(merged.tables_t, : 未使用 论点(竞争日期 = as.character(as.Date(as.yearmon(with(merged.tables_t, sprintf("%d-%02d", CompetitionOpenSinceYear, 竞赛OpenSinceMonth))))))
请注意,当我使用 data.frame 时,我得到了所需的结果:
> merged.tables_d$CompetitionDate<-as.character(as.Date(as.yearmon(with(merged.tables_d,sprintf("%d-%02d",CompetitionOpenSinceYear,CompetitionOpenSinceMonth)))))
结果应该是这样的:
> head(merged.tables_d$CompetitionDate)
[1] "2007-11-01" "2007-11-01" "2007-11-01" "2007-11-01" "2007-11-01" "2007-11-01"
事实上,我需要使用 data.table 而不是 data.frame,因为它的运行时间更快。
请问如何使用 data.table 获得相同的结果? 提前谢谢你
【问题讨论】:
-
您可以使用来自
tidyr的unite或来自base r的paste -
@MKR,请仅使用 data.table 操作给我完整的答案
-
请分享
dput(merged.tables_t)并将输出添加到您的问题中。这将使每个人都更容易提供帮助 -
@MKR,你可以看到需要的结果,
dput(merged.tables_t)给出了许多类似1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,的格式 -
我添加了一个答案来帮助你。看看吧。
标签: r