How to increase buffer size in R-function - r

i would like to implement a function in R which is able to increase the size of a buffer in a for-loop.
The overall-plan is to write a package, which uses a test- and a reference-shapefile. It should create a buffer around the reference shapefile and increases the size as long as necessary, to intersect the whole test-shapefile.
Therefore, i already wrote some code snippets to insert the shapefiles and create the first buffer:
require("rgeos")
require("rgdal")
l1=readOGR(dsn="C:/Maps", layer="osm_ms1")
l2=readOGR(dsn="C:/Maps", layer="osm_ms2")
proj4string(l2) = CRS("+init=epsg:31467") ## DHDN / 3-degree Gauss-Kruger zone 3
l2buffer <- gBuffer(l2, width=0.001, capStyle="ROUND")
plot(l2buffer, col="black")
lines(l2, col="red")
lines(l1, col="blue")
Until now, every works fine.
After that, i wanted to transfer this method to a for-loop with a buffer for every step:
i = 0.001
buffergrow = function(shape) {
for (k in 1:10) {
linebuffer[k] <- gBuffer(l2, width=i, capStyle="ROUND")
plot(linebuffer[k])
i = i+0.001
}
}
> buffergrow(l2)
Error in linebuffer[k] <- gBuffer(shape, width = i, capStyle = "ROUND") :
Object 'linebuffer' not found
As you can see, an error occurs when i call the function 'buffergrow' with 'l2' as the argument (shape). Does anybody has an idea why this happens? I tried already some other ideas, but i need some help.
Optionally / Additionally: Do you have some hints for me, regarding the further work for my overall plan?
Best regards,
Stefan

You have to initialize an object before accessing its subelements.
E.g.:
foo <- double(10)
for (i in 1:10) {
foo[i] <- i;
}
# or
linebuffer <- list()
for (i in 1:10) {
linebuffer[[i]] <- i;
}
But you don't need an object linebuffer in your usecase.
Try the following instead:
buffergrow = function(shape) {
for (k in 1:10) {
plot(gBuffer(l2, width=i, capStyle="ROUND"))
i = i+0.001
}
}
EDIT:
If you need to store the gBuffer results:
buffergrow = function(shape) {
i <- 1
linebuffer <- vector("list", 10)
for (k in 1:10) {
linebuffer[[k]] <- gBuffer(l2, width=i, capStyle="ROUND")
plot(linebuffer[[k]])
i = i+0.001
}
return(linebuffer)
}

Related

How to implement a function with a sum inside in R?

I am trying to define a function with a for loop and inside a conditional in R studio. Yesterday I was able with the help of another thread to devise this piece of code. The problem is that I want to sum the vector elements ma for any possible x, so that is inside the function l. This is a simpler case which I am trying to solve to adapt the original model. However, I do not know how to proceed.
ma<-rep(0,20)
l <- function(x, ma) {
for(i in seq_along(ma)) {
if(i %% 2 == 1) {
ma[i] <- i + x
} else {
ma[i] <- 0
}
}
return(ma)
}
My problem is that I would like to have the sum of i+x+0+i+x... for any possible x. I mean a function of the kind for any possible x.
Question:
Can someone explain to me how to implement such a function in R?
Thanks in advance!
I am going to update the original function:
Theta_alpha_s<-function(s,alpha,t,Basis){
for (i in seq_along(Basis)){
if(i%% 2==1) {Basis[i]=s*i^{-alpha-0.5}*sqrt(2)*cos(2*pi*i*t)}
else{Basis[i]=s*i^{-alpha-0.5}*sqrt(2)*sin(2*pi*i*t)}
}
return(Basis)
}
If you don't want to change the values in Basis, you can create a new vector in the function (here result) that you will return:
l = function(s,alpha,t,Basis){
is.odd = which(Basis %% 2 == 1)
not.odd = which(Basis %% 2 == 0)
result = rep(NA, length(Basis))
result[is.odd] = s*is.odd^{-alpha-0.5}*sqrt(2)*cos(2*pi*is.odd*t)
result[not.odd] = s*not.odd^{-alpha-0.5}*sqrt(2)*sin(2*pi*not.odd*t)
#return(result)
return(c(sum(result[is.odd]), sum(result[not.odd])))
}

confunsion in create if in R

I have a question how to make a IF
for (i in 1:12){
for (j in 1:12) {
if (i != j) {
var = x + b
}
else{ }
}}
"else" I need that when they are equal to continue with j + 1 example: if i = 4 and j = 4 then continue with j = 5 and continue counting until the end of j and continue the process of when i! = j
I think you don't understand what is going on in your code or you don't understand what for loops do. One "trick" you can do is to actually print what happens in your for loops so that you will have one idea of what is going on. You could also do this with a piece of paper.
As they already pointed you out, you don't need the else because the for already takes care of this.
for (i in 1:12){
print("-------------------------------")
valueI <- paste0("my i value is ",i)
print(valueI)
for (j in 1:12) {
valueJ <- paste0("my j value is ",j)
print(valueJ)
if (i != j) {
#var = x + b
diff <- paste0(i, " is different than ", j)
print(diff)
}
else{
}
}
}
This code is the same as yours and will generate a log that explains you what happens step from step, you could also use a debugger but seeing your struggles, better use this for now. What are you trying to calculate? I feel like you want to calculate the power of something...

R S3 cat() output from function

I've got a problem with output from S3 function. I try to overload "+" function to act with two vectors like with polynomial parameters. It's my university project. Code is below:
'+.ply' <- function(a,b){
size <- max(length(a$polynomial),length(b$polynomial))
size
aAdd <- a$polynomial
bAdd <- b$polynomial
if (length(aAdd) == size) {
aAdd = aAdd
} else {
length(aAdd) <- size
}
aAdd[is.na(aAdd)] <- 0
if (length(bAdd) == size) {
bAdd = bAdd
} else {
length(bAdd) <- size
}
bAdd[is.na(bAdd)] <- 0
cat("Polynomial of degree ", paste(length(aAdd+bAdd)-1),
" with coefficients ", paste(aAdd+bAdd))
}
Code is working fine, but in return it gives me output
*Polynomial of degree 3 with coefficients 3 4 6 3NULL*
I need to use cat in order to avoid [1] index which occurs while I'm using print, paste combo. I know that there are plenty threads about this problem, but I can't find any sollution for such problem during function overloading. I will be thankful for help.

Incorporating point error information into a distance function--how to do it in R?

I have been working with the proxy package in R to implement a distance measure that weights Euclidean distance by the propagated errors of each individual point. The formula to do this is
sqrt((xi - xj)2) + (yi - yj)2) + ...(ni - nj)2) ÷ sqrt((σxi2 + σxj2) + (σyi2 + σyj2) + ...(σni2 + σnj2)).
I was able to get proxy to work for me in a basic sense (see proxy package in R, can't make it work) and replicated plain Euclidean distance functionality, hooray for the amateur.
However, once I started writing the function for the error-weighted distance, I immediately ran into a difficulty: I need to read in the errors as distinct from the points and have them processed distinctly.
I know that R has very strong functionality and I'm sure it can do this, but for the life of me, I don't know how. It looks like proxy's dist can handle two matrix inputs, but how would I tell it that matrix X is the points and matrix Y is the errors, and then have each go to its appropriate part of the function before being ultimately combined into the distance measure?
I had been hoping to use proxy directly, but I also realized that it looks like I can't. I believe I was able to come up with a function that works. First, the distance function:
DistErrAdj <- function(x,y) {
sing.err <- sqrt((x^2) + (y^2))
sum(sing.err)
}
Followed, of course, by
library(proxy)
pr_DB$set_entry(FUN=DistErrAdj,names="DistErrAdj")
Then, I took code already kindly written from augix (http://augix.com/wiki/Make%20trees%20in%20R,%20test%20its%20stability%20by%20bootstrapping.html) and altered it to suit my needs, to wit:
boot.errtree <- function(x, q, B = 1001, tree = "errave") {
library(ape)
library(protoclust)
library(cluster)
library(proxy)
func <- function(x,y) {
tr = agnes((dist(x, method = "euclidean")/dist(q, method = "DistErrAdj")), diss = TRUE, method = "average")
tr = as.phylo(as.hclust(tr))
return(tr)
}
if (tree == "errprot") {
func <- function(x,y) {
tr = protoclust((dist(x, method = "euclidean")/dist(q, method = "DistErrAdj")))
tr = as.phylo(tr)
return(tr)
}
}
if (tree == "errdiv") {
func <- function(x,y) {
tr = diana((dist(x, method = "euclidean")/dist(q, method = "DistErrAdj")), diss=TRUE)
tr = as.phylo(as.hclust(tr))
return(tr)
}
}
tr_real = func(x)
plot(tr_real)
bp <- boot.phylo(tr_real, x, FUN=func, B=B)
nodelabels(bp)
return(bp)
}
It seems to work.

How to initialize R function during first run or whenever input changes

I'm new to R and have some trouble of understanding so called "envirionments" and way to use them properly. What I miss a lot in R language are static variables (like in Java).
I'm writing a program with couple of functions that will need to initialize during first run. To achieve this for each function I've created new environment which will be only accessed by this particular function (for example "f1" will be only accessed from inside "myfunction1").
What I don't like about my solution is that there is some additional code outside of function body and it's not too readable. Is there any simpler way to achieve the same? And if yes then it would be nice if you could provide me with modified example to show me how it works. Thank you.
f1 <- new.env()
f1$initialized <- FALSE
f1$o <- NULL
f1$length <- NULL
f1$compute
myfunction1 <- function(x) {
if(f1$initialized == FALSE){
f1$initialized <- TRUE
f1$compute <- 2*pi^2+3
}
if(is.null(f1$length) || f1$length!=length(x)){
f1$length <- length(x)
if(f1$length==2) {f1$o<-read.table("data_1.txt")}
else {f1$o<-read.table("data_2.txt")}
}
print("Lets print something!")
return(f1$o * f1$compute * x + 1000)
}
If you are familiar with Java then maybe using RefrenceClasses would be a good way to go. This seems to do what you are looking for:
myclass <- setRefClass('myclass', fields = list(initilized = 'logical',
o = 'data.frame',
len = 'numeric',
compute = 'numeric'))
#constructor
myclass$methods(initialize = function(initialized, len){
initilized <<- initialized
len <<- len
})
#method
myclass$methods(myfunction1 = function(x){
if(initilized == FALSE){
initilized <<- TRUE
compute <<- 2*pi^2+3
}
if(is.null(len) || len != length(x)){
len <<- length(x)
if(len==2) {o <<- read.table("data_1.txt")}
else {o <<- read.table("data_2.txt")}
}
print("Lets print something!")
return(o * compute * x + 1000)
})
obj <- myclass$new(FALSE, 0)
obj$myfunction1(2)
Check out ?ReferenceClasses for information on what's going on here (much more OOP styled and has some support for class inheritance, which sounds like what you want anyway).

Resources