I want to work out a simple recurrence relation in R but I cant find resources anywhere online that allows me to do this.
something simple like
for $n=1,2,3$
$X_0=3$
$X_n=X_{n-1}+5$
then print all $X_n$
I understand the basics for a for loop but it doesnt work for the left hand side of the loop, like i cant simply have
$for(i \hspace{2mm} in \hspace{2mm} 1:3)$
{
$X_0=3$
$X_n=X_{n-1}+5$
}
Like with any other language, you could use a for loop but then you're not using recursivity. The recursive version:
f <- function(n) { if (n==0) 3 else f(n-1)+5 }
Related
I have a command with six lines that I want to use several times. Therfore, I want to assign a name to this command and use it as a procedure instead of writing the whole command lines over and over.
In this case it is a <-rbind() command, but the issue is also more general.
modelcoeff<-rbind(modelcoeff,c(as.character((summary(mymodel)$terms[[2]])[[3]]),
as.character((((((summary(mymodel)$terms[[2]])[[2]])[[3]])[[3]])[[2]])[[3]]),
summary(mymodel)$coefficients[2,1],
summary(mymodel)$coefficients[2,4],
summary(mymodel)$coefficients[2,2],
summary(mymodel)$r.squared*100))
I would like to call something like rbindmodelcoeff and execute these command lines. How can I achieve this?
I tried to write a function, but it didn't seem to be the right approach.
A literal wrapping of your code into a function:
rbindmodelcoeff <- function(modelcoeff, mymodel) {
rbind(modelcoeff,
c(as.character((summary(mymodel)$terms[[2]])[[3]]),
as.character((((((summary(mymodel)$terms[[2]])[[2]])[[3]])[[3]])[[2]])[[3]]),
summary(mymodel)$coefficients[2,1],
summary(mymodel)$coefficients[2,4],
summary(mymodel)$coefficients[2,2],
summary(mymodel)$r.squared*100))
}
However, there are a couple changes I recommend:
call summary(mymodel) once, then re-use the results
you are using as.character on some of the objects but not all within the enclosing c(.), so everything is being converted to a character; to see what I mean, try c(as.character(1), 2); we can use a list instead to preserve string-vs-number
rbindmodelcoeff <- function(modelcoeff, mymodel) {
summ <- summary(mymodel)
rbind(modelcoeff,
list(as.character((summ$terms[[2]])[[3]]),
as.character((((((summ$terms[[2]])[[2]])[[3]])[[3]])[[2]])[[3]]),
summ$coefficients[2,1],
summ$coefficients[2,4],
summ$coefficients[2,2],
summ$r.squared*100))
}
But there are still some problems with this. I can't get it to work at the moment since I don't know the model parameters you're using, so as.character((summ$terms[[2]])[[3]]) for me will fail. With that, I'm always hesitant to hard-code so many brackets without a firm understanding of what is being used. It's out of scope for this question (which is being converting your basic code into a function), but you might want to find out how to generalize that portion a bit.
So I'm trying to build a simple stack of scaled cubes using a recursive function:
function stack(levels) = (
levels <= 0
? cube([1,1,1], center=true)
: union() {
cube([1,1,1], center=true);
translate([0, 0, 0.9]) scale([1, 1, 0.9]) stack(levels - 1);
}
);
stack(5);
Now for some reason I currently don't understand OpenSCAD tells me that I've got a syntax error in line 4, marking the editor like this:
Sadly the console only yields this output:
ERROR: Parser error in line 4: syntax error
ERROR: Compilation failed!
So it's somewhat hard for me to figure out what exactly I'm doing wrong.
I guess there's a way to do this using for, but I would consider a recursive approach more readable.
I'll try to do this with modules, and if that doesn't work I can resort to use for in combination with modules I suppose - it's more that I'd like this to work and find it very readable.
Update: So from the OpenSCAD User Manual I get this snippet:
I would tend to interpret this so that it is not possible to create a recursive structure the way I imagined.
Instead I could:
Use a helper function to generate the cube parameters and compute their union afterwards.
Rewrite the structure in terms of a for loop.
I'm uncertain whether my conviction is correct, but the reasoning is this:
I cannot create objects in a function because that would have an effect.
I cannot use a module recursively because it doesn't return a result and possibly the way variables work in OpenSCAD would interfere with the idea.
You can make a recursive module, the only problem there is the ternary operator takes values not objects:
module stack(levels) {
if(levels) {
cube([1,1,1], center=true);
translate([0, 0, 0.9]) scale([1, 1, 0.9]) stack(levels-1);
} else {
cube([1,1,1], center=true);
}
}
stack(5);
Here's another example: https://github.com/cashlo/OpenSCAN-Objects/blob/master/xmas-tree.scad
Suppose I want to create a method for a class I've created, but I don't have access to the code of the original function - I just want to build on top of it. Just to give a simple example that doesn't actually do anything:
x1<-1
class(x1)<-c("myclass",class(x1))
print.myclass<-function(x) {
x<-paste0(x,"foobar")
print(x)
}
print(x1)
If I try to run the last line, it throws the function into a loop and R eventually crashes. The solution I found was to add a line to the function that strips the new class name from x before passing it to the original function:
print.myclass<-function(x) {x<-paste0(x,"foobar"); class(x)<-class(x)[-1]; print(x)}
Is there a better/best practice way to do it?
I think your problem is that you create an infinite loop: print(print(...).
I don't know what you want to achieve but this might be what you are looking for:
x1 <- 1
class(x1) <- c("myclass",class(x1))
print.myclass <- function(x) print.default(x)
print(x1)
Perhaps you might want to look here
BTW: I don't think your solution really solves the problem. You just delete your new class entry which causes print not to use print.myclass.
For details see Hadley
Just started using Scilab, looks like a lot to learn but I am stuck at very first basic program. I need to display 1 to 10 numbers without using loop.
I know that using loop we can use this code to display numbers from 1 to 10:
for i = 1:10
disp(i)
end
But i need to display them without using any loop. In C programming it's a bit easy using recursive function but here i have tried alot and failed.
Please can any one help me out via code snippet.
I think a recursive call is still kind of a loop, but it could be done like this:
function recursivePrint(i, maxNumber)
if( i <= maxNumber )
disp(i)
recursivePrint(i+1, maxNumber)
end
endfunction
recursivePrint(1, 10);
Usually when people ask to write a function without a loop they mean something like:
disp(1:10)
disp(1)
disp(2)
disp(3)
disp(4)
disp(5)
disp(6)
disp(7)
disp(8)
disp(9)
disp(10)
Curious what you tried..
I have problem in using if else inside function, my code is like this:
ConvertWgtZooLS <- function(WgtZoo, LSWay, Pos){
If(LSWay == 0){
NewWgtZoo <- WgtZoo
}else{
BackPos <- BackMatrix(Pos,1)
NewWgtZoo<- Ifelse((Sign(WgtZoo) * Sign(BackPos) * LSWay)>=0, WgtZoo, 0)
}
return(NewWgtZoo)
}
However, when I run that in R, error message appears as:
"Error: unexpected '{' in:
"ConvertWgtZooLS <- function(WgtZoo, LSWay, Pos){
If(LSWay == 0){"
How can I resolve this? What is the syntax problem there? I checked many websites and seems the above if else syntax is correct.
Thanks a lot!
The error in your code is that you have used If instead of if, and R is case-sensitive. Thus, it is possible to have another function named If that does something different from if, and, as #danielkullmann points out, that function is exactly what R is looking for.
The error messages that R produces are not always the most helpful, but in this case, it does point you very close to the problem area. It shows you where it got "confused" but it's up to you to figure out why!
After you've fixed that first problem, you'll find another one (for the same reason) on line 6, where you have written Ifelse instead of ifelse.
One last point: R is pretty whitespace friendly, so it is good practice to leave some space in your code to help improve legibility, particularly with if and else statements. Here's why:
I find if (LSWay == 0) { easier to read than if(LSWay == 0){
When using an actual function, like sum(x), you do not usually add a space, making it easier to spot these conditional statements in large blocks of code.
The Google R Style Guide is an interesting read in this regard.