2016-08-11 128 views
0

你好我所面臨的問題,同時將時間戳轉換爲POSIXlt,稍後從此時間戳o需要提取年,月,日,小時,分,秒

2015-12-01 00:04:39 is my timestamp 

,這裏是我的嘗試

getwd() 
rm(list=ls()) 
library(ggplot2) 
library(plyr) 
library(reshape) 
library(scales) 
library(gridExtra) 
library(SparkR) 

Sys.setenv(SPARK_HOME="/usr/local/spark").libPaths(c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib"), .libPaths())) 

sc <- sparkR.init(master="local","RwordCount") 
args <- commandArgs(trailing = TRUE) 

sqlContext <- sparkRSQL.init(sc) 

df1 <- read.df(sqlContext, "hdfs://master:9000/test.csv", header='true', source = "com.databricks.spark.csv", inferSchema='true', stringsAsFactors = F) 


if("timestamp" %in% colnames(df1)){ 
    df1$pTime <- as.POSIXlt(df1$timestamp, format= "%Y-%m-%d %H:%M:%S") 
    }else { 
    df1$pTime <- as.POSIXlt(df1$Timestamp, format= "%Y-%m-%d %H:%M:%S") 
} 

但這裏得到錯誤不知道如何轉換 'DF1 $時間戳' 上課「POSIXlt」

後來我需要找出的年,月,DAYOFMONTH,開胃,分,秒爲我有這樣的片段

df1$Year <- df1$pTime$year-100 #Year 
df1$Month <- df1$pTime$mon+1 #Month 1-12 
df1$Day <- df1$pTime$mday #day of month 
df1$Hour <- df1$pTime$hour #0â??23: hours 
df1$Min <- df1$pTime$min 
df1$Sec <- df1$pTime$sec 
df1$WeekOfYear <- strftime(df1$pTime, format="%W") 

,我上面的腳本使用以下語法執行,

bin/spark-submit --packages com.databricks:spark-csv_2.11:1.3.0 /home/script/analysis.R 

**Error in as.POSIXlt.default(df1$timestamp, format = "%Y-%m-%d %H:%M:%S") : 
    do not know how to convert 'df1$timestamp' to class 「POSIXlt」 
    Calls: as.POSIXlt -> as.POSIXlt.default 
    Execution halted** 

我如何擺脫錯誤,任何幫助將不勝感激。 感謝

+0

我的代碼沒有出現任何錯誤。我嘗試了一個日期的角色矢量,例如你引用的那個。你應該給我們'str(df1)'。 – agenis

+0

因爲我在sparkR腳本中使用它。 –

回答

1

您可以通過

x <- Sys.time() 
format(x, format="%Y") 

例如提取日期時間值的部分。請參閱

?strptime 

適用於所有選項。

我不能重建你的問題的第一部分。什麼是你得到的錯誤信息?

1

您可以通過使用as.POSIXct

x <- as.POSIXct("2015-12-01 00:04:39") 

,然後使用lubridate包轉換您的時間戳,您可以

library(lubridate) 

year(x) 
#[1] 2015 
month(x) 
#[1] 12 
day(x) 
#[1] 1 
hour(x) 
#[1] 0 
minute(x) 
#[1] 4 
second(x) 
#[1] 39 
1

首先提取所有的信息,您可以使用索引你的data.frame不使用ifelse案例

df1[colnames(df1) %in% "timestamp"] 

將整列格式轉換爲2015-12-01 00:04:39

as.POSIXlt(strptime(as.character(df1[colnames(df1) %in% "timestamp"]), 
        format = "%Y-%m-%d %H:%M:%S"), 
      format = "%Y-%m-%d %H:%M:%S") 
相關問題