简体   繁体   English

将日期分为周和年

[英]Separate Date into week and year

Currently my dataframe has dates displayed in the 'Date' column as 01/01/2007 etc I would like to convert these into a week/year value ie 01/2007. 目前,我的数据框的“日期”列中显示的日期为01/01/2007,等等,我想将其转换为周/年的值,即01/2007。 Any ideas? 有任何想法吗? I have been trying things like this and getting no where... 我一直在尝试这样的事情,却一无所获...

enviro$Week <- strptime(enviro$Date, format= "%W/%Y")

You have to first convert to date, then you can convert back to the week of the year using format, for example: 您必须首先转换为日期,然后才能使用格式转换回一年中的星期,例如:

### Converts character to date
test.date <- as.Date("10/10/2014", format="%m/%d/%Y")

### Extracts only Week of the year and year
format(test.date, format="Week number %W of %Y")
[1] "Week number 40 of 2014"

### Or if you prefer
format(date, format="%W/%Y")
[1] "40/2014"

So, in your case, you would do something like this: 因此,对于您的情况,您将执行以下操作:

enviro$Week <- format(as.Date(enviro$Date, format="%m/%d/%Y"), format= "%W/%Y")

But remember that the part as.Date(enviro$Date, format="%m/%d/%Y") is only necessary if your data is not in Date format, and you also should put the right format parameter to convert your character to Date, if that is the case. 但是请记住,仅当您的数据不是日期格式时才需要as.Date(enviro$Date, format="%m/%d/%Y")部分,并且还应该输入正确的format参数来转换您的如果是这种情况,请输入Date的字符。

What is the class of enviro$Date ? enviro$Date的类别是什么? If it is of class Date there is probably a better way of doing this, otherwise you can try 如果它是Date类,则可能有更好的方法,否则您可以尝试

v <- strsplit(as.character(enviro$Date), split = "/")
weeks <- sapply(v, "[", 2)
years <- sapply(v, "[", 3)
enviro$Week <- paste(weeks, years, sep = "/")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM