Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying col type in Sparklyr (spark_read_csv)

Tags:

r

sparklyr

I am reading in a csv into spark using SpraklyR

schema <- structType(structField("TransTime", "array<timestamp>", TRUE),
                 structField("TransDay", "Date", TRUE))

 spark_read_csv(sc, filename, "path", infer_schema = FALSE, schema = schema)

But get:

Error: could not find function "structType"

How do I specify colunm types using spark_read_csv?

Thanks in advance.

like image 371
Levi Brackman Avatar asked Jan 04 '23 07:01

Levi Brackman


1 Answers

The structType function is from Scala's SparkAPI, in Sparklyr to specify the datatype you must pass it in the "column" argument as a list, suppose that we have the following CSV(data.csv):

name,birthdate,age,height
jader,1994-10-31,22,1.79
maria,1900-03-12,117,1.32

The function to read the corresponding data is:

mycsv <- spark_read_csv(sc, "mydate", 
                          path =  "data.csv", 
                          memory = TRUE,
                          infer_schema = FALSE, #attention to this
                          columns = list(
                            name = "character",
                            birthdate = "date", #or character because needs date functions
                            age = "integer",
                            height = "double"))
# integer = "INTEGER"
# double = "REAL"
# character = "STRING"
# logical = "INTEGER"
# list = "BLOB"
# date = character = "STRING" # not sure

For manipulating datetype you must use the hive date functions, not R functions.

mycsv %>% mutate(birthyear = year(birthdate))

Reference: https://spark.rstudio.com/articles/guides-dplyr.html#hive-functions

like image 153
Jader Martins Avatar answered Jan 08 '23 06:01

Jader Martins