我需要将一个10 to的固定宽度文件读到一个数据帧中。我如何在R中使用Spark来做呢?
假设我的文本数据如下:
text <- c("0001BRAjonh ",
"0002USAmarina ",
"0003GBPcharles")我希望前4个字符与数据框的列"ID“关联;从字符5-7关联到列"Country";从字符8-14关联到列"Name”
如果数据集很小,我会使用函数read.fwf,但情况并非如此。
我可以使用sparklyr::spark_read_text函数将该文件作为文本文件读取。但是我不知道如何正确地将文件的值赋给数据框。
发布于 2019-03-27 09:23:49
编辑:忘记说子串从1开始,数组从0开始,因为原因。
浏览并添加我在上面的专栏文章中提到的代码。
该过程是动态的,并且基于一个名为Input_Table的配置单元表。该表有5列: Table_Name、Column_Name、Column_Ordinal_Position、Column_Start和Column_Length。它是外部的,因此任何用户都可以更改、删除和删除文件夹位置中的任何文件。我从头开始快速构建,不需要实际的代码,一切都有意义吗?
#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:_*)https://stackoverflow.com/questions/55343522
复制相似问题