r中的粘贴功能

paste function in r

我认为这应该是一个非常容易解决的问题;但是,我在这里找不到它;而且,我在其他地方找到的说明没有用。我要做的就是使用简单的粘贴功能。

在我的数据框中,我有一个格式为 "yymmdd":

的日期变量
> str(g.2015.1990$DATE)
 int [1:60464] 150410 150411 150412 150420 150421 150422 150423 150424 150425 150426 ...

R 将其解释为整数,但我需要将其格式化为日期。当我进入 2000-2009 这十年时,我的问题就出现了。 R 删除前导 0。因此,2001-2009 的格式为 "ymmdd"; 2000 年 10 月到 12 月的格式为 "mmdd";并且,2000 年 1 月到 9 月的格式为 "mdd".

我想我可以将矢量分成四个部分(无论如何我必须逐年将它绑定到 assemble)并粘贴 none、一个、两个或前面三个 0(视情况而定)以创建一致的 6 位字符串,然后我可以将其转换为日期。

我还没有花时间将这个变量分解成上述部分,因为我还没有找到成功解决我的问题的方法;然而,这是我对变量的完整测试:

datex = paste("0", g.2015.1990$DATE, sep = "")
datex = paste(0, g.2015.1990$DATE, sep = "")
datex = paste("0", as.character(g.2015.1990$DATE), sep = "")
datex = paste(0, as.character(g.2015.1990$DATE), sep = "")

每一个returns同样的错误:

Error in View : 'names' attribute [1254] must be the same length as the vector [1]

请告诉我我做错了什么!我发誓这应该很容易解决。

to create a consistent, 6-digit character string that I can then convert to a date.

所以你需要:

datex <- sprintf("%06d", g.2015.1990$DATE)
## formatted string: 6-digit integer, padding 0 ahead

例子

sprintf("%06d", 150410)    ## 2015-04-10
# "150410"

sprintf("%06d", 90410)    ## 2009-04-10
# "090410"

sprintf("%06d",410)    ## 2000-04-10
[1] "000410"

如果您稍后想将 datex 转换为 Date 对象,请执行:

datex <- as.Date(datex, "%y%m%d")

例子

as.Date("150410", "%y%m%d")
# [1] "2015-04-10"

as.Date("090410", "%y%m%d")
# [1] "2009-04-10"

as.Date("000410", "%y%m%d")
# [1] "2000-04-10"

你想在这里 sprintf(),而不是 paste。然后你可以使用任何日期转换功能,但我喜欢 lubridate

# say you have 2009-10-11 and 2010-10-11, but yymmdd and numeric, so leading
# 0 is dropped on '09...
your_vec <- c(91011, 101011)

# convert to 6 char string (result: "091011" "101011")
new_vec <- sprintf('%06d', your_vec)

# but if you must use paste... (same result: "091011" "101011")
ifelse(nchar(your_vec) == 5, paste0('0', your_vec), your_vec)

# either way, now you can make it a date
library(lubridate)
ymd(new_vec)

# result:
# "2009-10-11 UTC" "2010-10-11 UTC"

(我选择了新的示例数据,因为你上面的实际上没有缺少前导零的问题)