In the code below I first create a rectangle from two horizontal lines and two vertical lines. Then I use st_polygonize to create a polygon. Finally, I use st_cast to create an object of class,
[1] "XY" "POLYGON" "sfg"
which is what I require. However, when I try to do something similar with a wave it fails. I create the wave polygon by duplicating a wave line, moving it up, and adding sides.
wave_gc plots OK but when I execute:
wave_poly <- class(st_cast(wave_gc, "POLYGON"))
wave_poly is empty. Why is this? How do I end up with an object of class
[1] "XY" "POLYGON" "sfg"
that works?
library(sf)
library(transformr)
# Rectangle #########################
# two vertical lines
v_lines <- st_multilinestring(list(rbind(c(0,0),c(0,1)), rbind(c(3,0),c(3,1))))
# two horizontal lines
h_lines <- st_multilinestring(list(rbind(c(0,0),c(3,0)), rbind(c(0,1),c(3,1))))
all_lines <- c(v_lines, h_lines)
rect_gc <- st_polygonize(all_lines)
rect_poly <- st_cast(rect_gc, "POLYGON")
class(rect_gc)
# [1] "XY" "GEOMETRYCOLLECTION" "sfg"
class(rect_poly)
# [1] "XY" "POLYGON" "sfg"
rect_poly
#################################################################
# Wave
################################################################
w1 <- path_waves(st = TRUE)[[1]]
w2 <- w1
# Add to second column, y values
w2[,2] <- w2[,2] + 0.1
# Vertical bars
nr <- nrow(w1)
v_bars <- st_multilinestring(list(rbind(c(w1[1, 1], w1[1, 2]), c(w2[1, 1], w2[1, 2])),
rbind(c(w1[nr, 1], w1[nr, 2]), c(w2[nr, 1], w2[nr, 2]))))
two_waves <- st_multilinestring(list(w1, w2))
full_wave <- c(v_bars, two_waves)
wave_gc = st_polygonize(full_wave)
wave_poly <- class(st_cast(wave_gc, "POLYGON"))
class(wave_gc)
# [1] "XY" "GEOMETRYCOLLECTION" "sfg"
plot(wave_gc)
wave_poly
# [1] "XY" "POLYGON" "sfg"
Related
plotrgnsize=function() {
m = par('mai')
o = par('omi')
dev.size()-c(
sum(m[c(2, 4)] + o[c(2, 4)])
, sum(m[c(1, 3)] + o[c(1, 3)])
)
}
The above function can return the plot region size when layout() is not called. When layout() is called, plotrgnsize() can not get the plot region size of each subfigure. How to get the subfigure plot region size?
layout(
mat=rbind(
3
, 2
, 1
)
, heights=c(3, 2, 1)
)
EDIT: Here is the sequence of commands to demonstrate the output.
R> plotrgnsize() # after calling plotrgnsize() once before, then dragged the plot window.
[1] 7.805454 5.767547
# ... then run the layout command shown above.
R> plotrgnsize()
[1] 8.227054 6.393147
R> plot(1:10)
R> plotrgnsize()
[1] 8.227054 6.393147
R> plot(1:10)
R> plotrgnsize()
[1] 8.227054 6.393147
R> plot(1:10)
R> plotrgnsize()
[1] 8.227054 6.393147
As you can see plotrgnsize() does not change when each subfigure is plotted. So it can not get the plot region size for each subfigure.
I'm new to R and want to write a code that generates random workouts. I have 4 character vectors that look like this
Compound_movements <- c('Hip thrust', 'Squat', 'Deadlift')
Abduction <- c('cable aduction', 'lying plated aduction')
Upper <- c('good mornings', 'kneeling squat')
Maxiums <- c('smith machine kick backs', 'cable kickbacks', 'single leg hipthrusts' )
G_H_tie_in <- c('stomp downs' )
I want to code that will pick out and then print 1 or 2 exercises from each vector. What are the best functions for this?
sample is what I think you need.
set.seed(42) # R-4.0.2
sample(Compound_movements, size = 1)
# [1] "Hip thrust"
sample(Compound_movements, size = 1)
# [1] "Hip thrust"
sample(Compound_movements, size = 1)
# [1] "Hip thrust"
sample(Compound_movements, size = 1)
# [1] "Hip thrust"
sample(Compound_movements, size = 1)
# [1] "Squat"
(Yes, apparently you'll do hip thrusts four times in a row ... random is random.)
If those are stored in a list of exercises, you can pick one from each with:
lst_of_exercises <- list(
Compound_movements = c('Hip thrust', 'Squat', 'Deadlift'),
Abduction = c('cable aduction', 'lying plated aduction'),
Upper = c('good mornings', 'kneeling squat'),
Maxiums = c('smith machine kick backs', 'cable kickbacks', 'single leg hipthrusts' ),
G_H_tie_in = c('stomp downs' )
)
sapply(lst_of_exercises, sample, size = 1)
# Compound_movements Abduction Upper Maxiums G_H_tie_in
# "Squat" "lying plated aduction" "good mornings" "single leg hipthrusts" "stomp downs"
And if you need to do other than the same number for all (e.g., 2 of one group, 1 of the others), then perhaps
Map(sample, lst_of_exercises, size = c(1,1,1,2,1))
# $Compound_movements
# [1] "Deadlift"
# $Abduction
# [1] "lying plated aduction"
# $Upper
# [1] "good mornings"
# $Maxiums
# [1] "smith machine kick backs" "cable kickbacks"
# $G_H_tie_in
# [1] "stomp downs"
So I read my shapefile easily:
shape<-readOGR(".","shapefile")
then if I do head(shape,1) I get the following result:
An object of class "SpatialLinesDataFrame"
Slot "data":
ID NAME PROJECT UP DOWN
0 1 X 05076 110468 38282
Slot "lines":
[[1]]
An object of class "Lines"
Slot "Lines":
[[1]]
An object of class "Line"
Slot "coords":
[,1] [,2]
[1,] 1824583 547917.9
[2,] 1824544 547437.1
Slot "ID":
[1] "0"
Slot "bbox":
min max
x 1824543.9 1824583.4
y 547437.1 547917.9
Slot "proj4string":
CRS arguments: NA
So getting the data is easy, I just do shape$NAME and I get all the names from the data.
But I don't know how to access the place where it says Slot "coords" which is what I want to access... or for that matter, how do I access things that are not on the data slot?
In other words, i want to read the shapefile and end up with a variable equal to 1824583, which is the top left value of the coords slot matrix.
Anyone can help?
We can use # to access the slots. Here I used the meuse dataset as an example.
library(sp)
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")
head(meuse#coords)
# x y
# 1 181072 333611
# 2 181025 333558
# 3 181165 333537
# 4 181298 333484
# 5 181307 333330
# 6 181390 333260
meuse#coords[1, 1]
# [1] 181072
I have a raster stack/brick in R containing 84 layers and I am trying to name them according to year and month from 199911 to 200610 (November 1999 to October 2006). However for some reason R keeps adding an "X" onto the beginning of any names I give my layers.
Does anyone know why this is happening and how to fix it? Here are some of the ways I've tried:
# Import raster brick
rast <- brick("rast.tif")
names(rast)[1:3]
[1] "MonthlyRainfall.1" "MonthlyRainfall.2" "MonthlyRainfall.3"
## Method 1
names(rast) <- paste0(rep(1999:2006, each=12), 1:12)[11:94]
names(rast)[1:3]
[1] "X199911" "X199912" "X20001"
## Method 2
# Create a vector of dates
dates <- format(seq(as.Date('1999/11/1'), as.Date('2006/10/1'), by='month'), '%Y%m')
dates[1:3]
[1] "199911" "199912" "200001"
# Set names
rast <- setNames(rast, dates)
names(rast)[1:3]
[1] "X199911" "X199912" "X200001"
## Method 3
names(rast) <- paste0("", dates)
names(rast)[1:3]
[1] "X199911" "X199912" "X200001"
## Method 4
substr(names(rast), 2, 7)[1:3]
[1] "199911" "199912" "200001"
names(rast) <- substr(names(rast), 2, 7)
names(rast)[1:3]
[1] "X199911" "X199912" "X200001"
To some extent I have been able to work around the problem by adding "X" to the beginning of some of my other data but now its reached the point where I can't do that any more. Any help would be greatly appreciated!
R won't allow the column to begin with a numeral so it prepends a character to avoid that restriction.
I have been trying plot the following gridded netcdf file: "air.1999.nc" found at the following website:
http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.html
I have tried the code below based on answers I have found here and elsewhere, but no luck.
library(ncdf);
temp.nc <- open.ncdf("air.1999.nc");
temp <- get.var.ncdf(temp.nc,"air");
temp.nc$dim$lon$vals -> lon
temp.nc$dim$lat$vals -> lat
lat <- rev(lat)
temp <- temp[nrow(temp):1,]
temp[temp==-32767] <- NA
temp <- t(temp)
image(lon,lat,temp)
library(maptools)
data(wrld_simpl)
plot(wrld_simpl, add = TRUE)
This code was from modified from the one found here: The variable from a netcdf file comes out flipped
Does anyone have any ideas or experience with using these type of netcdf files? Thanks
In the question you linked the whole part from lat <- rev(lat) to temp <- t(temp) was very specific to that particular OP dataset and have absolutely no universal value.
temp.nc <- open.ncdf("~/Downloads/air.1999.nc")
temp.nc
[1] "file ~/Downloads/air.1999.nc has 4 dimensions:"
[1] "lon Size: 144"
[1] "lat Size: 73"
[1] "level Size: 12"
[1] "time Size: 365"
[1] "------------------------"
[1] "file ~/Downloads/air.1999.nc has 2 variables:"
[1] "short air[lon,lat,level,time] Longname:Air temperature Missval:32767"
[1] "short head[level,time] Longname:Missing Missval:NA"
As you can see from these informations, in your case, missing values are represented by the value 32767 so the following should be your first step:
temp <- get.var.ncdf(temp.nc,"air")
temp[temp=="32767"] <- NA
Additionnaly in your case you have 4 dimensions to your data, not just 2, they are longitude, latitude, level (which I'm assuming represent the height) and time.
temp.nc$dim$lon$vals -> lon
temp.nc$dim$lat$vals -> lat
temp.nc$dim$time$vals -> time
temp.nc$dim$level$vals -> lev
If you have a look at lat you see that the values are in reverse (which image will frown upon) so let's reverse them:
lat <- rev(lat)
temp <- temp[, ncol(temp):1, , ] #lat being our dimension number 2
Then the longitude is expressed from 0 to 360 which is not standard, it should be from -180 to 180 so let's change that:
lon <- lon -180
So now let's plot the data for a level of 1000 (i. e. the first one) and the first date:
temp11 <- temp[ , , 1, 1] #Level is the third dimension and time the fourth.
image(lon,lat,temp11)
And then let's superimpose a world map:
library(maptools)
data(wrld_simpl)
plot(wrld_simpl,add=TRUE)