在 SparkR 中应用带有正则表达式模式的 withColumn 函数:重新格式化 DataFrame 中的字符串列

Applying withColumn function with regular expression patterns in SparkR: reformat a string column in a DataFrame

Background/overview:

我正在尝试将 gsub 函数应用于我已从以下方式加载到 Spark 中的 SparkR DataFrame 的列:

dat <- read.df(sqlContext, "filepath", header='false', inferSchema='true')

我正在使用 Spark 1.6.1,数据文件在作为 SparkR DataFrame 读入之前存储为 parquet 文件。

问题核心:

我的 DataFrame (DF) 中有一个名为 period 的列,该列由当前为字符串形式 MM/DD/YYYY 的日期组成,例如2001 年 9 月 23 日。我想将其转换为 SparkR 中的日期类型对象。然而,我可以说的是,SparkR 中的函数 castas.Date 只能将格式为 MM-DD-YYYY 的字符串日期转换为日期类型对象。

在尝试将我的 period 列转换为可以重铸为日期数据类型的形式时,我尝试将 gsub R 函数与 withColumn SparkR 一起使用函数创建一个新的 DF,dat2,附加列,nperiodperiod 的所有行条目从形式 MM/DD/YYYY 转换为 MM-DD-YYYY .我的第一次尝试是通过下面的代码给出的,但我收到了以下错误消息: dat2 <- withColumn(dat, "nperiod", gsub("/", "-", dat$period))

dat2 <- withColumn(dat, "nperiod", gsub("/", "-", dat$period)) Error in withColumn(dat, "nperiod", gsub("/", "-", dat$period)) : error in evaluating the argument 'col' in selecting a method for function 'withColumn': Error in as.character.default(x) : no method for coercing this S4 class to a vector

也许这只是我对核心 Spark 如何在 SparkR 中使用 S4 数据 类 的无知,但我不确定如何解释此错误消息或如何继续对 gsub 进行故障排除解决这个问题的方法。

或者,一种更 hackier 的方法是将 MM/DD/YYYY period 列拆分为三个单独的列。然而,即便如此,我也在 SparkR 环境中苦苦挣扎。我已经创建了一个名为 separated 的新 DF,它由一个列 (period_sep) 组成,period 组件的行用逗号分隔,尽管我我不完全确定这是什么数据结构,或者下一步将其分为三个单独的列。

> separated <- selectExpr(dat, "split(period, '/') AS period_sep")
> head(separated)
    period_sep
1 01, 01, 2000
2 02, 01, 2000
3 03, 01, 2000
4 04, 01, 2000
5 05, 01, 2000
6 06, 01, 2000

如果有人想知道如何朝这两个方向中的任何一个方向前进,或者如果有更好的方法来做到这一点,我们将不胜感激。此外,如果我似乎不理解一些有助于解释正在发生的事情的基本 Spark 概念,请随时分享任何相关信息。

编辑:添加有关我尝试使用转换时收到的错误的信息:

当我尝试使用 withColumnperiod 转换为日期 dtype 时,我收到以下错误消息:

dat2 <- withColumn(dat, "nperiod", cast(dat$period, "date")) Error in withColumn(dat, "nperiod", cast(dat$period, "date")) : error in evaluating the argument 'col' in selecting a method for function 'withColumn': Error in cast(dat$period, "date") : error in evaluating the argument 'x' in selecting a method for function 'cast': Error in column(callJMethod(x@sdf, "col", c)) : error in evaluating the argument 'x' in selecting a method for function 'column': Error in callJMethod(x@sdf, "col", c) : Invalid jobj 2. If SparkR was restarted, Spark operations need to be re-executed.

您不能在此上下文中使用标准 R 函数,但在 Spark 1.6 中您可以使用内置日期处理函数:

df <- createDataFrame(sqlContext, data.frame(ds=c('04/02/2015', '03/10/2014')))

dt <- cast(cast(unix_timestamp(df$ds, 'MM/dd/yyyy'), 'timestamp'), 'date')

df %>% withColumn('date', dt) %>% head()
##           ds       date
## 1 04/02/2015 2015-04-02
## 2 03/10/2014 2014-03-10