"Welcome to R Coding Workshop!"[1] "Welcome to R Coding Workshop!"
sfPPOL 6805: GIS for Spatial Data Science
print() and comment out"Welcome to R Coding Workshop!"[1] "Welcome to R Coding Workshop!"
print("Welcome to R Coding Workshop!")[1] "Welcome to R Coding Workshop!"
2025[1] 2025
⌘ + /: Commenting# 2025
# command + forward slash to comment out<-: initialize a variable and assign a value
# variable_name <- variable_value
x <- 1984
y <- "World Geodetic System"class()print(class(x))[1] "numeric"
print(class(y))[1] "character"
z <- class(x) == class(y)
print(class(z))[1] "logical"
Ways to create a vector
c()seq(from, to, by):v1 <- c(
"Bryce Canyon", "Canyonlands", "Arches", "Zion", "Capitol Reef"
)
v2 <- 1:5
v2[1] 1 2 3 4 5
v3 <- seq(21.9, 25.3, 0.1)
is.vector(v2)[1] TRUE
# v1 <- c(
# "Bryce Canyon", "Canyonlands", "Arches", "Zion", "Capitol Reef"
# )
v1[1][1] "Bryce Canyon"
v1[-1][1] "Canyonlands" "Arches" "Zion" "Capitol Reef"
v4 <- 1:12
bool_v4 <- v4 > 8
v4[bool_v4][1] 9 10 11 12
names(v4) <- month.abb
v4["Jan"]Jan
1
data.frame as a collection of column vectorsWays to create a df
mth_df <- data.frame(
mth = 1:12,
mth_str = month.abb
)
mth_df| mth | mth_str |
|---|---|
| 1 | Jan |
| 2 | Feb |
| 3 | Mar |
| 4 | Apr |
| 5 | May |
| 6 | Jun |
| 7 | Jul |
| 8 | Aug |
| 9 | Sep |
| 10 | Oct |
| 11 | Nov |
| 12 | Dec |
mth_df |> class()[1] "data.frame"
data.frame attributesutah_df <- data.frame(
national_park = v1,
lat = c(
37.640621053549125, 38.478777627059635, 38.6167568289248,
37.200271934321734, 38.291603924096385
),
lon = c(
-112.16957627116382, -109.8251716515892, -109.61982474559946,
-112.98700616100083, -111.2619347149233
)
)head(utah_df, 2)| national_park | lat | lon |
|---|---|---|
| Bryce Canyon | 37.64062 | -112.1696 |
| Canyonlands | 38.47878 | -109.8252 |
# nrow() and ncol()
dim(utah_df)[1] 5 3
colnames(utah_df)[1] "national_park" "lat" "lon"
data.frameprint(utah_df[, 1])[1] "Bryce Canyon" "Canyonlands" "Arches" "Zion" "Capitol Reef"
print(utah_df[1, ]) national_park lat lon
1 Bryce Canyon 37.64062 -112.1696
print(utah_df$national_park)[1] "Bryce Canyon" "Canyonlands" "Arches" "Zion" "Capitol Reef"
utah_df[["national_park"]][1] "Bryce Canyon" "Canyonlands" "Arches" "Zion" "Capitol Reef"
summary(utah_df) national_park lat lon
Length:5 Min. :37.20 Min. :-113.0
Class :character 1st Qu.:37.64 1st Qu.:-112.2
Mode :character Median :38.29 Median :-111.3
Mean :38.05 Mean :-111.2
3rd Qu.:38.48 3rd Qu.:-109.8
Max. :38.62 Max. :-109.6
class(utah_df[1])[1] "data.frame"
sf and a maplibrary(sf)Linking to GEOS 3.13.0, GDAL 3.8.5, PROJ 9.5.1; sf_use_s2() is TRUE
library(mapview)
utah_sf <- st_as_sf(
utah_df,
coords = c('lon', 'lat'),
crs = 4326
)
utah_sf |> mapview()utah_sf| national_park | geometry |
|---|---|
| Bryce Canyon | POINT (-112.1696 37.64062) |
| Canyonlands | POINT (-109.8252 38.47878) |
| Arches | POINT (-109.6198 38.61676) |
| Zion | POINT (-112.987 37.20027) |
| Capitol Reef | POINT (-111.2619 38.2916) |