如何将整数列转换为日期:
DATE PRCP
1: 19490101 25
2: 19490102 5
3: 19490118 18
4: 19490119 386
5: 19490202 38
到这样的表:
days month years PRCP
答案 0 :(得分:10)
我们可以使用extract
library(tidyr)
extract(df, DATE, into=c('YEAR', 'MONTH', 'DAY'),
'(.{4})(.{2})(.{2})', remove=FALSE)
# DATE YEAR MONTH DAY PRCP
#1 19490101 1949 01 01 25
#2 19490102 1949 01 02 5
#3 19490118 1949 01 18 18
#4 19490119 1949 01 19 386
#5 19490202 1949 02 02 38
答案 1 :(得分:5)
这是使用正则表达式的另一种方式:
else if segue.identifier == "openingHours" {
var vc = segue.destinationViewController
var controller = vc.popoverPresentationController
if controller != nil {
controller?.delegate = self
}
}
@IBAction func openingHoursTap(sender: UITapGestureRecognizer) {
performSegueWithIdentifier("openingHours", sender: self)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
答案 2 :(得分:4)
我建议你使用lubridate包:
require(lubridate)
df[, DATE := ymd(DATE)]
df[, c("Day", "Month", "Year") := list(day(DATE), month(DATE), year(DATE))]
df[, DATE := NULL]
答案 3 :(得分:4)
另一种选择是使用 tidyr 包中的separate
:
library(tidyr)
separate(df, DATE, c('year','month','day'), sep = c(4,6), remove = FALSE)
导致:
DATE year month day PRCP
1: 19490101 1949 01 01 25
2: 19490102 1949 01 02 5
3: 19490118 1949 01 18 18
4: 19490119 1949 01 19 386
5: 19490202 1949 02 02 38
基础R中的两个选项:
@coffeinjunky在评论中提及substr
的1):
df$year <- substr(df$DATE,1,4)
df$month <- substr(df$DATE,5,6)
df$day <- substr(df$DATE,7,8)
2)与as.Date
和format
:
df$DATE <- as.Date(as.character(df$DATE),'%Y%m%d')
df$year <- format(df$DATE, '%Y')
df$month <- format(df$DATE, '%m')
df$day <- format(df$DATE, '%d')
答案 4 :(得分:2)
首先,我会使用DATE
将Date
列转换为as.Date()
类型,然后使用对format()
的调用构建新的data.frame:
df <- data.frame(DATE=c(19490101,19490102,19490118,19490119,19490202),PRCP=c(25,5,18,386,38),stringsAsFactors=F);
df$DATE <- as.Date(as.character(df$DATE),'%Y%m%d');
data.frame(day=as.integer(format(df$DATE,'%d')),month=as.integer(format(df$DATE,'%m')),year=as.integer(format(df$DATE,'%Y')),PRCP=df$PRCP);
## day month year PRCP
## 1 1 1 1949 25
## 2 2 1 1949 5
## 3 18 1 1949 18
## 4 19 1 1949 386
## 5 2 2 1949 38