for loop with unequal variables
I have a 2 variables with various lengths. I want to create a for loop that only calculate the sum for two equal values. If the values aren't equal to each other, the variable b must be updated with +1. Is there 开发者_如何学编程a way to create this? I thougth something like this:
a <- c(1,2,3,4,5)
b<- c(1,7,2,3,6,4,5)
j <- 1
test<- matrix()
for( i in 1:length(a)) {
if(a[i] == b[j]){
result <- a[i] + b[j]
test[[i]]<-matrix(result)
j <- j + 1}
else {
j <- j +1
}
1 + 1 = TRUE
2 + 7 + FALSE +1
2 + 2 = TRUE
3 + 3 = TRUE
4 + 6 = FALSE +1
4 + 4 = TRUE
5 + 5 = TRUE
Thank you all!
I think that this is the right solution for this variables. The only requirement is that all values from variable a need to provent in variable b.
a <- c(1,2,3,4,5)
b<- c(1,7,2,3,6,4,5)
match(a,b)
test <- matrix()
for(i in 1:length(a)){
if (a[i] == b[i]) {
result <- a[i] + b[i]
test[i]<- result
}
else {
c<- which(b == a[i])
result <- a[i] + b[c]
test[i]<- result
}
}
Not totally sure what you are trying to do but how does this work?
a <- c(1,2,3,4,5)
b<- c(1,7,2,3,6,4,5)
test<- matrix()
for( i in 1:length(a)) {
for (j in 1:length(b)){
if (a[i] == b[j]) {
result <- a[i] + b[j]
test[i]<- result
break()
}
}
}
> test
[1] 2 4 6 8 10
I think you need to define what you expect a lot more clearly. If all you want is to double the values of 'a' which appear in 'b' (since summing two equal things is twice one of them), then all you need is doubs<-vector()
j=1
for (i in 1:length(a)){
if (length(which(a[i]==b)) >0 ) {doubs[j]=2*a[i];j<-j+1}
}
But: do you only want to store the first match, or all matches? E.g. a = 1 and b = c(1,2,1,3,1). And you need to read up on "==" vs. is.equal or you will one day be sorry.
精彩评论