如何编辑 SparkDataFrame 的模式?
How to edit the schema of a SparkDataFrame?
我有一个 SparkDataFrame,我想在其上使用 dapply() 应用一些函数并添加一个新列。
在 SparkR 中应用 dapply 期望模式与被调用函数的输出相匹配。
例如,
#Creating SparkDataFrame
sdf<-as.DataFrame(iris)
#Initiating Schema
schm<-structType(structField("Sepal_Length", "double"),structField("Sepal_Width", "double"),structField("Petal_Length","double"),structField("Petal_Width","double"),structField("Species","string"),structField("Specie_new","string"))
#dapply code
sdf2<-dapply(sdf,function(y)
{
y$Specie_new<-substr(y$Specie,nchar(y$Species)-1,nchar(y$Species))
return(y)
},schm)
有没有更好的方法来做同样的事情?我的意思是如果我有 100 列那么这将不是一个可行的选择,在这些情况下我应该怎么做?
可以说更好的方法是避免 dapply
对于像这种简单的情况。您可以轻松地使用简单的正则表达式来获得相同的结果:
regexp_extract(df$Species, "^.*(.{2})$", 1)
或 Spark SQL 函数的组合(SparkR::substr
、SparkR::length
)。
不过,您仍然可以轻松地重用现有架构来创建新架构。假设您要添加新字段 foo
:
foo <- structField("foo", "string")
只需提取现有字段的字段并将它们合并:
do.call(structType, c(schema(df)$fields(), list(foo)))
可能有点晚了,但从 Spark v2.2.0 开始,添加到 zero323 的答案中:
#Initiating Schema
added_schm <- structType(structField("Specie_new","string"))
schm <- do.call(structType, append(schema(sdf)$fields(), added_schm$fields()))
我有一个 SparkDataFrame,我想在其上使用 dapply() 应用一些函数并添加一个新列。
在 SparkR 中应用 dapply 期望模式与被调用函数的输出相匹配。 例如,
#Creating SparkDataFrame
sdf<-as.DataFrame(iris)
#Initiating Schema
schm<-structType(structField("Sepal_Length", "double"),structField("Sepal_Width", "double"),structField("Petal_Length","double"),structField("Petal_Width","double"),structField("Species","string"),structField("Specie_new","string"))
#dapply code
sdf2<-dapply(sdf,function(y)
{
y$Specie_new<-substr(y$Specie,nchar(y$Species)-1,nchar(y$Species))
return(y)
},schm)
有没有更好的方法来做同样的事情?我的意思是如果我有 100 列那么这将不是一个可行的选择,在这些情况下我应该怎么做?
可以说更好的方法是避免 dapply
对于像这种简单的情况。您可以轻松地使用简单的正则表达式来获得相同的结果:
regexp_extract(df$Species, "^.*(.{2})$", 1)
或 Spark SQL 函数的组合(SparkR::substr
、SparkR::length
)。
不过,您仍然可以轻松地重用现有架构来创建新架构。假设您要添加新字段 foo
:
foo <- structField("foo", "string")
只需提取现有字段的字段并将它们合并:
do.call(structType, c(schema(df)$fields(), list(foo)))
可能有点晚了,但从 Spark v2.2.0 开始,添加到 zero323 的答案中:
#Initiating Schema
added_schm <- structType(structField("Specie_new","string"))
schm <- do.call(structType, append(schema(sdf)$fields(), added_schm$fields()))