首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在R中使用Spark读取固定宽度的文件

如何在R中使用Spark读取固定宽度的文件
EN

Stack Overflow用户
提问于 2019-03-26 01:33:37
回答 1查看 181关注 0票数 0

我需要将一个10 to的固定宽度文件读到一个数据帧中。我如何在R中使用Spark来做呢?

假设我的文本数据如下:

代码语言:javascript
复制
text <- c("0001BRAjonh   ",
"0002USAmarina ",
"0003GBPcharles")

我希望前4个字符与数据框的列"ID“关联;从字符5-7关联到列"Country";从字符8-14关联到列"Name”

如果数据集很小,我会使用函数read.fwf,但情况并非如此。

我可以使用sparklyr::spark_read_text函数将该文件作为文本文件读取。但是我不知道如何正确地将文件的值赋给数据框。

EN

回答 1

Stack Overflow用户

发布于 2019-03-27 09:23:49

编辑:忘记说子串从1开始,数组从0开始,因为原因。

浏览并添加我在上面的专栏文章中提到的代码。

该过程是动态的,并且基于一个名为Input_Table的配置单元表。该表有5列: Table_Name、Column_Name、Column_Ordinal_Position、Column_Start和Column_Length。它是外部的,因此任何用户都可以更改、删除和删除文件夹位置中的任何文件。我从头开始快速构建,不需要实际的代码,一切都有意义吗?

代码语言:javascript
复制
#Call Input DataFrame and the Hive Table. For hive table we make sure to only take correct column as well as the columns in correct order.
val inputDF       = spark.read.format(recordFormat).option("header","false").load(folderLocation + "/" + tableName + "." + tableFormat).rdd.toDF("Odd_Long_Name")
val inputSchemaDF = spark.sql("select * from Input_Table where Table_Name = '" + tableName + "'").sort($"Column_Ordinal_Position")

#Build all the arrays from the columns, rdd to map to collect changes a dataframe col to a array of strings. In this format I can iterator through the column.
val columnNameArray    = inputSchemaDF.selectExpr("Column_Name").rdd.map(x=>x.mkString).collect
val columnStartArray   = inputSchemaDF.selectExpr("Column_Start_Position").rdd.map(x=>x.mkString).collect
val columnLengthArray  = inputSchemaDF.selectExpr("Column_Length").rdd.map(x=>x.mkString).collect

#Make the iteraros as well as other variables that are meant to be overwritten
var columnAllocationIterator = 1
var localCommand             = ""
var commandArray             = Array("") 

#Loop as there are as many columns in input table
while (columnAllocationIterator <= columnNameArray.length) {
  #overwrite the string command with the new command, thought odd long name was too accurate to not place into the code
  localCommand = "substring(Odd_Long_Name, " + columnStartArray(columnAllocationIterator-1) + ", " + columnLengthArray(columnAllocationIterator-1) + ") as " + columnNameArray(columnAllocationIterator-1) 

  #If the code is running the first time it overwrites the command array, else it just appends
  if (columnAllocationIterator==1) {
    commandArray = Array(localCommand)
  } else {
    commandArray = commandArray ++ Array(localCommand)
  }

  #I really like iterating my iterators like this
  columnAllocationIterator = columnAllocationIterator + 1
}

#Run all elements of the string array indepently against the table
val finalDF = inputDF.selectExpr(commandArray:_*)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55343522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档