循环重铸 SparkR 数据框中所有列的类型 and/or 应用函数

Re-casting types of all column in SparkR data frame in a loop and/or apply function

SparkR 1.4.1一起使用结构数据框时:

printSchema(dta)
root
 |-- date: timestamp (nullable = true)
 |-- valA: float (nullable = true)
 |-- valB: float (nullable = true)
 |-- ...

我想将现有列的 all 转换为字符串, 不明确引用每一列名字.

期望的方法

所需的方法将遍历所有列:

# Quickly creating new data frame
dtaTmp <- select(dta, "date")

# Looping through each column of old data frame and adding string equivalent
# to a newly created data frame
for (i in seq_along(columns(dtaTmp))) {
    print(i)
    x  <- cast(eval(parse(text = paste(sep = "$", "dtaTmp", columns(dtaTmp)[i]))), 
           "string")
    dtaTmp <- withColumn(dtaTmp, (columns(dtaTmp)[i], x)
}

失败并出现错误:returnStatus == 0 is not TRUE。实际上,我正在寻找一种解决方案,使我能够 运行 相当于 SparkR 数据帧上的 sapply(mtcars, as.character)

想要的结果

一个新的数据框应该是这样的结构:

printSchema(desiredDta)
root
 |-- date: string(nullable = true)
 |-- valA: string(nullable = true)
 |-- valB: string(nullable = true)
 |-- ...

您在 1.4 分支中遇到了一个错误,其中 withColumn 保留了重复的列名。最简单的解决方案是使用带有列列表的单个 select

select(df, lapply(columns(df), function(x) alias(cast(df[[x]], "string"), x)))