I have 2 vectors of numbers. The vector "v" shows when a process starts in seconds. Vector u shows how much time does the proces in the vector u works.
I want to creeate a vector saying how many process are working at each second.
so this toy example: I create a vector "total" thats starts in second 0 (nevermind the end of the vector) and I will save in each position how many processes work in that second. So for example, in the first position of the vector(time 0) my code says I will have 1 process.
v <- c(0,1,2,3,4,5)
u <- c(1.2, 0.1, 1.2, 1, 0.5, 0)
j = 1
total <- rep(0, times = 10)
begin <- integer()
end <- integer()
repeat{
begin<- v[j] +1
end <- begin + u[j]%/%1
for(i in begin:end){
if(total[i] == 0){ total[i] <-1}
else total[i] = total[i] +1
}
if(j ==length(v)) break
j = j+1
}
total
[1] 1 2 1 2 2 1 0 0 0 0
I got this error(not here, in the real case):
Error in begin:end : argument of length 0
(I tried using an if in case begin = end) but "for" should work for only one position.
What can be happening??
You can use seq.int instead of : in this case. For example:
for (a in seq.int(from=3, to=3)) {
print(a)
}
[1] 3
Related
This question already has answers here:
Generate N random integers that sum to M in R
(3 answers)
Closed 10 days ago.
I want to create an array, then assign a value to each place until the sum of values in the array equals a given total. Once the maximum value is reached the rest of the array can be 0. So to start:
years <- 20 # total length of array
N <- array(0, years) # make array
tot <- 10 # Total I want to stop at
max.size <- 3 # maximum value to put in the array
So the result may look something like: N = c(1,3,0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0)
I think a while statement would work, similar to this question, but not sure how to get there. Also, I think this question has the pieces I need, but am struggling to put them into my context.
random.sample <- function(x) { repeat {
# do something
i <- sample(0:max.size, 1)
x <- i
# exit if the condition is met
if (sum(x) == tot) break } return(x) }
random.sample(N)
Thanks for your time.
A simple function using cumsum and ifelse would do the job without requiring costly loops. The last clause just ensures the the numbers add to tot
f <- function(len, tot, max.size) {
x <- sample(0:max.size, len, replace = TRUE)
res <- ifelse(cumsum(x) > tot, 0, x)
if(sum(res) < tot) {
res[(cumsum(res) == sum(res)) & res == 0][1] <- tot - sum(res)
}
res
}
Testing
f(len = 20, tot = 10, max.size = 3)
#> [1] 3 3 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
I am trying to find the row and column numbers of a matrix once I have the entry number. For example if I am trying to find a 0 in a matrix full of numbers I would try something like this
test_array <- array(1,c(30,30))
test_array[200] <- 0
counter <- 0
for(i in test_array){
counter <- counter + 1
if(i == 0){
print(counter)
}
}
200
So now I know that at position 200 I have a 0 but how do I check where it is in terms of its row and col.
Something like (15, 8)
You can use the arr.ind argument in which:
which(test_array == 0, arr.ind = TRUE)
#> row col
#> [1,] 20 7
I am trying to solve the question of compare triplets in R posted on hackerrank
Although I have outlined the entitre steps still its not giving correct result not in hackerrank and in RStudio also . can anyone tell me
A reproducible example
m = data.frame(ints = as.integer())
m <- structure(rbind(m,c(5,6,7)), .Names = names(m))
m <- structure(rbind(m,c(3,6,10)), .Names = names(m))
names(m) = c("no1","no2","no3")
enter## the output gives m as below
`no1 no2 no3
1 5 6 7
2 3 6 10
## I need to compare the corresponding values in both rows
#if m[1,1] != m[2,1] then I need to store 1 in a vector or dataframe
#if m[1,2] != m[2,2] then I need to store 1 in a vector or dataframe
#if m[1,3] != m[2,3] then I need to store 1 in a vector or dataframe
#so We will get output as [1,1]
## defining a vector to store output as below
g = c(0,0,0)
g = c(0,0,0)
> g
[1] 0 0 0
> g[1]
[1] 0
## so my answer is as below
if(m[1,1]== m[2,1]))
{
print("nothing")
}
else
{
(g[1] = 1)
}
if((m[1,2]==m[2,2]))
{
print("nothing")
}
else
{
(g[2] = 1)
}
if((m[1,3]==m[2,3]))
{
print("nothing")
}
else
{
(g[3] = 1)
}
g = data.frame()
g = c(0,0,0)
I get the following errors after every else
Error: unexpected 'else' in " else"
also g even takes value for middle value which it should never take
g
[1] 1 1 1
Can anyone explain what is going on why it is still placing 1 for middle value.
In R an end of line marks the end of an instruction unless there are open parenthesis, open braces or an unfinished instruction, such as else to signify otherwise.
Try
if(m[1,1]== m[2,1]) {
print("nothing")
} else
{
(g[1] = 1)
}
Or shorter
if(m[1,1]== m[2,1])
print("nothing") else
g[1] = 1
Your problem in any case is better solved by:
g <- as.numeric(m[1,] != m[2,])
# [1] 1 0 1
I am trying to determine the first decimal place value different from zero. For example, in 0.0000082109314 it would be the sixth (or million-th), where there is an 8.
I thought about a loop, but it's not working. So I'd rather ask in pseudo-code:
d = runif(100, min = 1e-10, max = 1e-5) # Toy data with 100 elements in a vector
position = rep(0, 100) # Starting an empty vector to place results
for(j in 1:100){ # Looping through d
for(i in 1:10){ # Exponents from 1 to 10
if(d[j]]) * 10^i >= 1) # First power of 10 turning the value > or = 1
position[j] = i # Assign i to the position
stop the looping through i and move on to the next j
}
}
So I need the loop to stop replacing the i value as soon as the condition is fulfilled. Otherwise, any higher value of i will also meet the condition, and it won't return the desired first position different from zero.
I know about break and next, but how could I use them (or other commands) here?
The issue is to at some point within the loop (when the condition is met) to ask R to 1. Save the index, and 2. Move on to the next j.
position = rep(0, 100)
for(j in 1:100){
for(i in 1:10){
if(d[j]]) * 10^i >= 0) position[j] = i AND next
else
CONTINUE with i
}
}
break will kick you out of your current loop. It won't go all the way to the top level so if you use it inside of the loop indexed by i it will basically just kick you to the next value for j and restart i at 1.
Just as a note if you're going to have multiple conditions inside of your if statement make sure to wrap all of them in curly braces.
for(j in 1:3){
for(i in 1L:6L){
# The result of this if statement is that we skip this iteration
# when i==2.
if(i == 2){
next
}
# The result of this if statement is that we kick out of the
# for loop indexed by i. The result being that we reach the end
# of the code block for the for loop indexed by j so if we aren't
# finished iterating over all of the values for j we go to the next
# value for j and start the for loop with i all over again.
if(i == 5){
break
}
# Just print out what i and j are equal to. We do this after the
# if statements so any iteration that isn't stopped by the if
# statements will end up printing a result.
print(sprintf("i: %i j: %i", i, j))
}
}
gives the output
[1] "i: 1 j: 1"
[1] "i: 3 j: 1"
[1] "i: 4 j: 1"
[1] "i: 1 j: 2"
[1] "i: 3 j: 2"
[1] "i: 4 j: 2"
[1] "i: 1 j: 3"
[1] "i: 3 j: 3"
[1] "i: 4 j: 3"
so by using next I skip every iteration where i==2 and by using break I stop anything for i>=5 and move on to the next value for j
If you were having troubles getting break to work with your code you'd need to post what you actually tried. There were issues other than 'break' in your code (you use d[j]] notice the mismatched square braces and I think you messed up your parenthesis on your if statement). This is what I think you wanted:
d = runif(100, min = 1e-10, max = 1e-5) # Toy data with 100 elements in a vector
position = rep(0, 100) # Starting an empty vector to place results
for(j in 1:100){ # Looping through d
for(i in 1:10){ # Exponents from 1 to 10
if((d[j] * 10^i) >= 1){ # First power of 10 turning the value > or = 1
position[j] = i # Assign i to the position
break
}
}
}
An approach that avoids loops would be:
convert numbers to scientfic format and into a character string
split the string
extract the exponential coefficient
For your example it looks like this (var1 = your input data, place is the resulting decimal place):
var1<-0.0000082109314
var1<-as.character(format(var1, scientific = T))
place<-strsplit(var1,"e")
place<-abs(as.numeric(place[[1]][2]))
(It is assumed that you have values << 1. Input data for large values must be interpreted differently, of course).
If you want to use loops, I think this sort of problem is an excellent candidate for a while loop because you don't know in advance how many iterations you will need. (They are also much more likely to start running forever due to a small typo, requiring you to restart your R session.)
x = 0.0000082109314
zero_first = TRUE
exponent = -1
while(zero_first) {
exponent = exponent + 1
if(x * 10^exponent >= 1) zero_first = FALSE
}
exponent
# [1] 6
This could replace your inner for loop. Of course, it's risky so it's probably best to do some input checking.
I want to iterate a loop only for some values so I am using this:
present <- c(3,5,7,8)
for(i in present)
{
print(i)
}
which gives me
[1] 3
[1] 5
[1] 7
[1] 8
however I need to jump to the next value within the loop, say I dont want 5 to be printed in above example.
I cannot use next since I want it in nested for like this
present <- c(3,5,7,8)
for(i in present)
{
k <- i
"Jump to next value of present"
while(k < "The next value for i should come here")
{
k <- k + 1
print(k)
}
}
The output would be 3 4 5 6 7 8 but the condition must check value of k if it exceeds next value of i.
Is there anyway to accomplish this?
I'll take help of C to explain further,
for(i=0; i < 10; i++)
{
for(k=i;k <= i+1;k++)
{
printf("%d", k);
}
}
The link contains output of above code
http://codepad.org/relkenY3
It is easy in C since next value is in sequence, but here next value is not known, hence the problem.
What you should do is loop through two vectors:
x <- head(present, -1)
# [1] 3 5 7
y <- tail(present, -1)
# [1] 5 7 8
and the function to do that is mapply (have a look at ?mapply). A close translation of your pseudo-code would be:
invisible(mapply(function(x, y) while(x < y) {x <- x + 1; print(x)}, x, y))
but maybe you'll find this more interesting:
mapply(seq, x + 1, y)
I suspect the answer is to use seq_along and use it as an index into "present", but as others have pointed out your code does not promise to deliver what you expect, even with that simple modification. The K <- K=1 assignment jumps ahead too far to deliver a value of 3 at any point and the termination condition is likewise not clear. It turns into an infinite loop in the form you construct. Work with this;
present <- c(3,5,7,8)
for(i in seq_along(present))
{
k <- i
while(k < length(present) )
{
k <- k + 1
print(present[k])
}
}