For loop in R is printing twice - r

I'm fairly new to programming and am avidly trying to learn R. I am attempting to solve the classic "Fizzbuzz" problem in R and have almost figured out a way, but my loop is printing twice. Tried debugging and searching, but I can't seem to find anything. Any suggestions?
tl;dr Do you know why this for loop prints twice?
fizzbuzz = function(n){
if ( n %% 15 == 0 ) {
print("Fizzbuzz")
} else
if ( n %% 5 == 0 ) {
print("buzz")
} else
if ( n %% 3 == 0 ) {
print("Fizz")
} else {
print(n)
}
}
for (a in 1:100)
print(fizzbuzz(a))

Because you call print twice, once in the function and once in the loop. Remove the print in the loop and it only prints once.
for (a in 1:100)
fizzbuzz(a)

You are printing the result of fizzbuzz and inside the function. Try this:
for (a in 1:100)
fizzbuzz(a)

Related

R loop checking condition X times and break if not met

I'd like to create kind of dependency between R and database and for that I'm trying to create a loop which is checking if a date in one column from a database is equal to today's date, if yes then run main statement, if not wait 5mins and try again (max 24 times) then break. I'm stucked with the latter, if someone could advice that would be helpful, thanks!
if(lubridate::date(table$db_date) == Sys.Date()){
print(1)
} else {
Sys.sleep(300)
# and repeat the loop 24 times until statement is TRUE, if not then break
}
If you have an upper limit for the number of iterations, you should use a for loop:
for (i in seq_len(24)) {
if(lubridate::date(table$db_date) == Sys.Date()){
print(1)
break
} else {
Sys.sleep(300)
}
}
Very primitive but maybe something like this:
i=1 # establish global variable
while (T) {
if(lubridate::date(table$db_date) == Sys.Date()){
print(1)
# break
}
if(i < 24 & lubridate::date(table$db_date) != Sys.Date()) { # check both statements
i <<- i+1 # update global variable
Sys.sleep(0.1) # and repeat the loop 24 times until statement is TRUE, if not then break
}
else{break}
}

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...

How to setup a recursive lapply for specific values ex.w[i] == n[i]?

Background
I'm developing a function that takes in a value for w between 1 and 3 and returns n values from one of 3 distributions.
The problem I am having is when n or w are not of length 1. So I've added 2 parameters nIsList and wIsList to create the functionality I want. The way I want this to work is as follows:
(Works as needed)
If nIsList ex( c(1,2,3) ) return a list equivalent to running consume(w,1), consume(w,2), consume(w,3)
(Works as needed)
If wIsList ex( c(1,2,3) ) return a list equivalent to running consume(1,n), consume(2,n), consume(3,n)
(Doesn't work as needed)
If nIsList ex(1,2,3) and wIsList ex(1,2,3)
return a list equivalent to running consume(1,1), consume(2,2), consume(3,3). Instead, I get a list equivalent to running [consume(1,1), consume(1,2), consume(1,3)], [consume(2,1), consume(2,2), consume(2,3)], [consume(3,1),consume(3,2), consume(3,3)]
I understand why I am getting the results I am getting. I just can't seem to figure out how to get the result I want. (As explained above)
Question
I want the function to provide a list for each element in w and n that is consume(w[i], n[i]) when wIsList & nIsList are True. Is there a way to do that using lapply?
The code:
library("triangle")
consume <- function(w, n=1, nIsList=F, wIsList=F){
if(!nIsList & !wIsList){
if(w==1){
return(rtriangle(n,0.3,0.8))
}else if(w==2){
return(rtriangle(n,0.7,1))
}else if(w==3){
return(rtriangle(n,0.9,2,1.3))
}
}
else if(nIsList & !wIsList){
return(sapply(n, consume, w=w))
}
else if(nIsList & wIsList){
return(lapply(n, consume, w=w, wIsList=T))
}
else if(!nIsList & wIsList){
return(lapply(w, consume, n))
}
}
Note: I am having trouble summarizing this question. If you have any suggestions for renaming it please let me know and I will do so.
Thanks to JPC's comment, using mapply does the trick. The new code is as follows:
consume <- function(w, n=1){
nIsList <- length(n) > 1 # Change based on JPC's second comment
wIsList <- length(w) > 1 # Change based on JPC's second comment
if(!nIsList & !wIsList){
if(w==1){
return(rtriangle(n,0.3,0.8))
}else if(w==2){
return(rtriangle(n,0.7,1))
}else if(w==3){
return(rtriangle(n,0.9,2,1.3))
}
}
else if(nIsList & !wIsList){
return(sapply(n, consume, w=w))
}
else if(nIsList & wIsList){
return(mapply(consume,w,n)) ## Updated portion
}
else if(!nIsList & wIsList){
return(lapply(w, consume, n))
}
}

Iteration over for loop in r

I am programming R and am confronted with the following syntax errorĂ–
Here is the code:
for (i in (1:7)) {for (index in seq(i,56,8)) {values[[length(values)+1]] <- c(ADDLINEORDER[index]) } time_series_values[[length(time_series_value)+1]] <- values}
Error: unexpected symbol in "for (i in (1:7)) {for (index in seq(i,56,8)) {values[[length(values)+1]] <- c(ADDLINEORDER[index]) } time_series_values"
what I want is: lets say that there is a vector (1,5,6,7,3,9) as input
As I result I want to have it like ((1,6,3),(5,7,9))
1 5 are the starting points, I want it to be iterated by 2 so (1, 6, 9) are together in one list.
Thanks
Missing semicolon. You pasted this into one line from something that was more than one line?
for (i in (1:7)) {for (index in seq(i,56,8)) {values[[length(values)+1]] <- c(ADDLINEORDER[index]) }; time_series_values[[length(time_series_value)+1]] <- values}
#Spacedman has found the problem. Formatting properly also fixes it:
for ( i in (1:7) ) {
for ( index in seq(i, 56, 8) ) {
values[[ length(values) + 1 ]] <- c( ADDLINEORDER[index] )
}
time_series_values[[ length(time_series_value) + 1 ]] <- values
}

Resources