R data.table将日期列转换为月份
我有以下玩具R data.table将日期列转换为月份,r,data.table,posixct,posixlt,R,Data.table,Posixct,Posixlt,我有以下玩具数据。表 x = data.table(dt = c('2015-01-01','2015-02-01','2016-04-01')) 我试图在表中添加一个额外的列,其中包含日期的三个字母缩写。我试过了 x$dt = strptime(x$dt,'%b') 但它返回了以下内容,一个警告和一个空字段 Warning messages: 1: In `[<-.data.table`(x, j = name, value = value) : Supplied 9 ite
数据。表
x = data.table(dt = c('2015-01-01','2015-02-01','2016-04-01'))
我试图在表中添加一个额外的列,其中包含日期的三个字母缩写。我试过了
x$dt = strptime(x$dt,'%b')
但它返回了以下内容,一个警告和一个空字段
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
Supplied 9 items to be assigned to 3 items of column 'dt' (6 unused)
2: In `[<-.data.table`(x, j = name, value = value) :
Coerced 'list' RHS to 'character' to match the column's type. Either change the target column to 'list' first (by creating a new 'list' vector length 3 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'character' (e.g. 1L, NA_[real|integer]_, as.*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please.
> x
dt mnth
1: c(NA, NA, NA)
2: c(NA, NA, NA)
3: c(NA, NA, NA)
警告消息:
1:在`[中我们可以使用格式
format(strptime(x$dt, '%Y-%m-%d'), '%b')
或者正如@Frank提到的,格式.Date
可以应用于Date
类
format(as.Date(x$dt), "%b")
我们可以使用格式
format(strptime(x$dt, '%Y-%m-%d'), '%b')
或者正如@Frank提到的,格式.Date
可以应用于Date
类
format(as.Date(x$dt), "%b")
示例中没有“mnth”。如果dt
是列,格式(strptime(x$dt,%Y-%m-%d'),“%b”)
更正/编辑了问题。您的解决方案在@akrun.Thank下有效。或者:x[,mnth:=months(strptime(dt,%Y-%m-%d'))]
示例中没有“mnth”。如果dt
是列,格式(strptime(x$dt,'%Y-%m-%d'),'%b')
更正/编辑了该问题。您的解决方案在@akrun.Thank.or:x[,mnth:=months(strtime(dt,%Y-%m-%d'))]
有一个格式化.Date
方法,并且as.Date
正确解析字符串,因此格式化(as.Date(x$dt),%b”)
是另一个选项。或者,正如Jaap所提到的,月份(as.Date(x$dt),abbr=TRUE)
有一个格式.Date
方法,as.Date
正确解析字符串,所以格式(as.Date(x$dt),%b”)
是另一个选项。或者,正如Jaap所提到的,月份(as.Date(x$dt),abbr=TRUE)