SparkR新手求助:如何将字段列表转换为StructType对象
在SparkR中获取DataFrame的StructType Schema及字段列表
确认Schema类型
你通过schema(output_count)获取的结果已经是StructType类型了——从str(schema)的输出能看到,该对象的class明确标记为structType,这说明你已经拿到了目标类型的schema。
提取字段列表
要得到字段列表,直接调用schema对象的fields()方法即可:
# 获取DataFrame的StructType schema schema <- schema(output_count) # 提取字段列表 fields <- schema$fields() # 查看字段详情 fields
执行后会输出类似如下的字段集合:
[[1]] StructField(name = "word", type = "StringType", nullable = TRUE) [[2]] StructField(name = "count", type = "StringType", nullable = TRUE)
扩展:遍历字段属性
如果需要单独查看每个字段的具体属性(名称、数据类型、是否可空),可以遍历fields列表:
for (field in fields) { cat("字段名:", field$name(), "| 数据类型:", field$dataType(), "| 是否可空:", field$nullable(), "\n") }
内容的提问来源于stack exchange,提问作者carmel
相关产品推荐
相关产品推荐

