将年/星期名称转换为r中的日期



我有以下数据框架的列名,格式为年/周

cols = colnames(vci1981.df)
[1] "gid"     "xcoord"  "ycoord"  "col"     "row"     "gwno"    "country" "km2"     "1981035" "1981036"
[11] "1981037" "1981038" "1981039" "1981040" "1981041" "1981042" "1981043" "1981044" "1981045" "1981046"
[21] "1981047" "1981048" "1981049" "1981050" "1981051" "1981052"

注释:1981年- 0xx周

如何将它们转换成相应的年-月格式?

示例:1981-035 = 1981-08

我尝试了与这里相同的方法将年/日的名称转换为r中的日期没有成功。

cols = ymd(parse_date_time(cols[9:length(cols)], orders="yw"))

这里有NA

cols = as.Date(cols[9:length(cols)], "%Y%W")

我得到了不对应的值:[1]"1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";[9], 1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";1981 - 06 - 29";[17]"1981 - 06 - 29";"1981 - 06 - 29">

试试这个:

## Creating the Dataframe
cols = c( "gid","xcoord","ycoord","col","row","gwno","country","km2","1981035","1981036",
"1981037","1981038","1981039","1981040","1981041","1981042","1981043","1981044","1981045",
"1981046","1981047","1981048","1981049","1981050","1981051","1981052"
)
df = data.frame(ColNames = cols)
## Creating empty list
df1=list()
df2=list()
## For loop to extract the year and the week
for (i in 9:nrow(df)){
a = substring(df$ColNames[i],1,4)
b = substring(df$ColNames[i],5,nchar(df$ColNames[i]))
df1 = append(df1,a)
df2 = append(df2,b)
}
## unlisting all lists
df1=unlist(df1)
df2=unlist(df2)
## Converting month number to digit month number
df2 = sprintf("%02d",sapply(strsplit(df2, ''), function(x) sum(as.numeric(x))))

## Replacing original values with new formatted values
cols[9:length(cols)] = paste(df1,"-",df2, sep="")

输出
> cols
[1] "gid"     "xcoord"  "ycoord"  "col"     "row"     "gwno"    "country" "km2"     "1981-08" "1981-09" "1981-10" "1981-11" "1981-12"
[14] "1981-04" "1981-05" "1981-06" "1981-07" "1981-08" "1981-09" "1981-10" "1981-11" "1981-12" "1981-13" "1981-05" "1981-06" "1981-07"

最新更新