Iteration over for loop in r - 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
}

Related

Getting "comparison of these types is not implemented" error while trying to compare two numbers in a list

I have a bubble sort function that looks like this:
print_sorted_array <- function(arr)
{
len <- length(arr)
for (i in 1:len){
j <- i
while((j > 1)){
if ((arr[j] < arr[j-1])){
temp <- arr[j]
arr[j] <- arr[j-1]
arr[j-1] <- temp
}
j <- j - 1
}
}
return(arr)
}
When I try to call this function
print_sorted_array(list(5, 16, 8, 2))
I get this error:
Error in arr[j] < arr[j - 1] :
comparison of these types is not implemented
I tried debugging it but couldn't figure out the RStudio debugger as I'm very new to this. I would appreciate any help, thanks!
Nevermind, using as.integer() on both list elements in the if statement worked. Still don't know why it wasn't integer in the first place but stopped caring.

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])))
}

Multiple conditions in if statements in R

I am trying to cut down a list of gene names that I have been given. I'm trying to eliminate any repetitive names that may be present but I keep getting an error when running my code:
counter=0
i=0
j=0
geneNamesRevised=array(dim=length(geneNames))
for (i in 0:length(geneNamesRevised))
geneNamesRevised[i]=""
geneNamesRevised
for (i in 1:length(geneNames))
for (j in 1:length(geneNamesRevised))
if (geneNames[i]==geneNamesRevised[j])
{
break
}
else if ((j==length(geneNamesRevised)-1) &&
(geneNames[i]!=geneNamesRevised[j]))
{
geneNamesRevised[counter]=geneNames[i]
counter++
}
The error message is a repetitive string of :
the condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be used
and this error message is for the last "else if" statement that has the '&&'.
Thank you!
Why not just
geneNamesRevised <- unique( geneNames )
... which returns a shortened list. There is also a duplicated function that can be used to remove duplicates when negated.
There are a few problems in your code.
1) The else is incorrectly specified - or not :) thanks #Mohsen_Fatemi
2) & is usually what you need rather than &&
3) counter++ isn't R
Copy the code below and see if it runs
for (i in 1:length(geneNames)){
for (j in 1:length(geneNamesRevised)){
if (geneNames[i]==geneNamesRevised[j])
{
break
} else {
if ((j==length(geneNamesRevised)-1) & (geneNames[i]!=geneNamesRevised[j]))
{
geneNamesRevised[counter]=geneNames[i]
counter <- counter + 1
}
}
}
}
Edit
4) also you were missing braces for your fors
use & instead of && ,
else if ((j==length(geneNamesRevised)-1) & (geneNames[i]!=geneNamesRevised[j]))

Error message in Bubble sort code in R language

I did some programming work on R language to do the bubble sort. Sometimes it works perfectly without any error message, but sometimes, it shows "Error in if (x[i] > x[i + 1]) { : argument is of length zero". Can any one help me check whats wrong with it? I have attached my code below
example <- function(x) {
n <- length(x)
repeat {
hasChanged <- FALSE
n <- n - 1
for(i in 1:n) {
if ( x[i] > x[i+1] ) {
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
hasChanged <- TRUE
cat("The current Vector is", x ,"\n")
}
}
if ( !hasChanged ) break;
}
}
x <-sample(1:10,5)
cat("The original Vector is", x ,"\n")
example(x)
The error occurs because you are iteratively decreasing n. Depending on the original vector's order (or lack thereof), n can reach the value of 1 after the last change. In that case, a further reduction of n in the next iteration step addresses the value x[0], which is undefined.
With a minimal correction your code will work properly, without giving error messages. Try to replace the line
if ( !hasChanged ) break;
with
if ( !hasChanged | n==1 ) break
Basically you have two termination criteria: Either nothing has been changed in the previous iteration or n is equal to one. In both cases, a further iteration won't change the vector since it is already ordered.
By the way, in R programming you don't need a semicolon at the end of a command. It is tolerated/ignored by the interpreter, but it clutters the code and is not considered good programming style.
Hope this helps.

Pause print of large object when it fills the screen [duplicate]

This question already has answers here:
Equivalent to unix "less" command within R console
(5 answers)
Closed 8 years ago.
Say I want to print a large object in R, such as
x <- 1:2e3
When I print x, the R console fills the screen with its elements and, since it doesn't fit all in the screen, it will scroll down. Then I have to scroll back up to see everything that went off screen.
What I would like is to have a command that would print x and stop when the screen fills, requiring the user to do something (like press enter) in order to have another screen full of data displayed. What I have in mind is something similar to MS DOS's dir /p command. Is there such a thing?
As suggested by #baptiste, this solution, page(x, method = 'print'), doesn't really solve my problem. To be more clear, what I would like is a solution that wouldn't involve printing the object in another window, as this would disrupt my workflow. If I didn't care for this, I'd just use View() or something similar.
Here is a quick and dirty more function:
more <- function(expr, lines=20) {
out <- capture.output(expr)
n <- length(out)
i <- 1
while( i < n ) {
j <- 0
while( j < lines && i <= n ) {
cat(out[i],"\n")
j <- j + 1
i <- i + 1
}
if(i<n) readline()
}
invisible(out)
}
It will evaluate the expression and print chunks of lines (default to 20, but you can change that). You need to press 'enter' to move on to the next chunk. Only 'Enter' will work, you can't just use the space bar or other keys like other programs and it does not have options for searching, going back, etc.
You can try it with a command like:
more( rnorm(250) )
Here is an expanded version that will quit if you type 'q' or 'Q' (or anything starting with either) then press 'Enter', it will print out the last lines rows of the output if you type 'T' then enter, and if you type a number it will jump to that decile through the output (e.g. typing 5 will jump to half way through, 8 will be 80% of the way through). Anything else and it will continue.
more <- function(expr, lines=20) {
out <- capture.output(expr)
n <- length(out)
i <- 1
while( i < n ) {
j <- 0
while( j < lines && i <= n ) {
cat(out[i],"\n")
j <- j + 1
i <- i + 1
}
if(i<n){
rl <- readline()
if( grepl('^ *q', rl, ignore.case=TRUE) ) i <- n
if( grepl('^ *t', rl, ignore.case=TRUE) ) i <- n - lines + 1
if( grepl('^ *[0-9]', rl) ) i <- as.numeric(rl)/10*n + 1
}
}
invisible(out)
}

Resources