i used following tutorial for learning R programming language
R programming language
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt+1
if(cnt > 5) {
break
}
}
but when i run this code, it gave me the following error
> if(cnt > 5) {
+ break
+ }
Error: object 'cnt' not found
>
this example was taken from tutorial itself, what is wrong in given code?
Related
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.
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.
I'm trying to do many conditional events in R but im getting the warning:
Warning messages:
1: In if (closeV > openV) { :
the condition has length > 1 and only the first element will be used
2: In if ((highV - closeV) < Minimum) { :
the condition has length > 1 and only the first element will be used
3: In if ((openV - lowV) > Threshold) { :
the condition has length > 1 and only the first element will be used
4: In if (((openV - lowV) < Threshold)) { :
the condition has length > 1 and only the first element will be used
5: In if ((closeV - openV) < Threshold) { :
the condition has length > 1 and only the first element will be used
6: In if ((closeV - lowV) < (Threshold * 2)) { :
the condition has length > 1 and only the first element will be used
this is a huge nest of ifs, it is not optimized right now but i cant get it to work because of that warning.
There are around of 40 ifs in that function, any idea of what i need to do to get around this warning?
The code looks something like this
if(closeV>openV)#1 First we check if we have a positive value
{
if((highV-closeV)<Minimum)
{
if((openV-lowV) >Threshold)
{
if((closeV-openV)<Threshold)
{
#3.1 This is a Hammer with positive movement
if((closeV-lowV)<(Threshold*2))
{
#3.1.1 not much movement
return(X*2)
}
else if((closeV-lowV)>(Treshold*2))
{
#3.1.2 a lot of movement
return(X*3)
}
}
else if((closeV-openV)>Threshold)
{
#3.2 Hammer but with a lot of movement
if((closeV-lowV)<(Threshold*2))
{
#3.2.1 not much movement
return(X)
}
else if((closeV-lowV)>(Treshold*2))
{
#3.2.2 a lot of movement
return(X*5)
}
}
}
else if(((openV-lowV)<Threshold)
and it keeps on going through a lot of possibilites
The issue is not the nested if-statements, but rather the data structure you feed into them: The warning tells you that the comparison operator is only applied to the first element of the data structure you feed into the if-statements.
While
a = seq(1, 10, 1)
b = seq(0, 18, 2)
if (a>b){
print(a)
} else{
print(b)
}
throws the same warning messages you get,
a = seq(1, 10, 1)
b = seq(0, 18, 2)
for (i in 1:10) {
if (a[i]>b[i]){
print(a[i])
} else{
print(b[i])
}
}
in contrast evaluates smoothly.
Also, please notice that although both pieces of code are evaluated, they give very different results.
I have the following code:
first.moves <- function()
{
go.first <- readline("Do you want to go first? (Y/N) ")
if (go.first == "Y" || go.first == "y")
{
game <- altern.moves()
}
else
{
game <- move(game,1,1)
}
return(game)
}
altern.moves <- function()
{
plyr.mv <- as.numeric(readline("Please make a move (1-9) "))
game <- move(game,plyr.mv,0)
cmp.mv <- valid.moves(game)[1]
game <- move(game,cmp.mv,1)
return(game)
}
#game
game <- matrix(rep(NA,9),nrow=3)
print("Let's play a game of tic-tac-toe. You have 0's, I have 1's.")
(game <- first.moves())
repeat
{
game <- altern.moves()
print(game)
}
When I run the part after #game in batch mode neither does R stop to wait for "Do you want to go first? (Y/N)" nor does it repeat the repeat block. Everything works fine on its own and when I click through it line-by-line.
What am I doing wrong and how can I remedy the situation to have a decent program flow but with user interaction? (or do I really have to click through this part of the code line-by-line? I hope not...)
Add this to the beginning of your code:
if (!interactive()) {
batch_moves <- list('Y', 5, 2) # Add more moves or import from a file
readline <- (function() {
counter <- 0
function(...) { counter <<- counter + 1; batch_moves[[counter]] }
})()
}
Now you get
> readline()
[1] "Y"
> readline()
[1] 5
> readline()
[1] 2
EDIT: Optionally, to clean up (if you are running more scripts), add rm(readline) to the end of your script.
EDIT2: For those who don't like <<-, replace counter <<- counter + 1 with assign('counter', counter + 1, envir = parent.env(environment())).
I am a Phd student in the university of Padua and I am trying to write a little script (the first!) in R cran v. 3.0.1 to make a simulation on epidemiology.
I'd like to change the values of a vector of 883 values basing on a neighbour matrix constructed with nb2mat from a shapefile: if i and j (two cells) are neighbour (matrix) and i or j have a positive value in the vector, I'd like to transform the value of both i and j to 1 (positive), otherwise the value of i and j should remain 0. When I launch the next little script:
for(i in 1:883)
{ for(j in 1:883)
{ if(MatriceDist[i,j] > 0 & ((vectorID[i] > 0 | vectorID[j] > 0)) {
vectorID[i] = 1 & vectorID[j] = 1
print(vectorID)
} } }
the answer from the software is:
Error: unexpected '{' in:
" { for(j in 1:883)
{ while(MatriceDist[i,j] > 0 & ((vectorID[i] > 0 | vectorID[j] > 0)) {"
I think that it is an error in the statement for if but I can not understand how to solve it...
Thank you everyone!
Elisa
check your brackets :-)
for(i in 1:883) {
for(j in 1:883) {
if(MatriceDist[i,j] > 0 & (vectorID[i] > 0 | vectorID[j] > 0)) { vectorID[i] = 1 & vectorID[j] = 1 print(vectorID)
}
}
}
you had one ( to mucch before vectorID in your if statement.
please double check is the condition now specified in the statement is still the one you require.
btw: for loops are very slow in R. If you know the end size of vectorID, try pre-allocating the full matrix. That will speed things up a little bit.