|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | +# contributor license agreements. See the NOTICE file distributed with |
| 4 | +# this work for additional information regarding copyright ownership. |
| 5 | +# The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | +# (the "License"); you may not use this file except in compliance with |
| 7 | +# the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | +library(SparkR) |
| 19 | + |
| 20 | +# Initialize SparkSession |
| 21 | +sparkR.session(appName = "SparkR-DataFrame-example") |
| 22 | + |
| 23 | +# Create a simple local data.frame |
| 24 | +localDF <- data.frame(name=c("John", "Smith", "Sarah"), age=c(19, 23, 18)) |
| 25 | + |
| 26 | +# Convert local data frame to a SparkDataFrame |
| 27 | +df <- createDataFrame(localDF) |
| 28 | + |
| 29 | +# Print its schema |
| 30 | +printSchema(df) |
| 31 | +# root |
| 32 | +# |-- name: string (nullable = true) |
| 33 | +# |-- age: double (nullable = true) |
| 34 | + |
| 35 | +# Create a DataFrame from a JSON file |
| 36 | +path <- file.path(Sys.getenv("SPARK_HOME"), "examples/src/main/resources/people.json") |
| 37 | +peopleDF <- read.json(path) |
| 38 | +printSchema(peopleDF) |
| 39 | +# root |
| 40 | +# |-- age: long (nullable = true) |
| 41 | +# |-- name: string (nullable = true) |
| 42 | + |
| 43 | +# Register this DataFrame as a table. |
| 44 | +createOrReplaceTempView(peopleDF, "people") |
| 45 | + |
| 46 | +# SQL statements can be run by using the sql methods |
| 47 | +teenagers <- sql("SELECT name FROM people WHERE age >= 13 AND age <= 19") |
| 48 | + |
| 49 | +# Call collect to get a local data.frame |
| 50 | +teenagersLocalDF <- collect(teenagers) |
| 51 | + |
| 52 | +# Print the teenagers in our dataset |
| 53 | +print(teenagersLocalDF) |
| 54 | + |
| 55 | +# Stop the SparkSession now |
| 56 | +sparkR.session.stop() |
0 commit comments