I have problem to create a empty vector in R, and save the results of another vector into them. This is my code:
k<-vector(mode = "numeric", length = 0)
for (j in length(Pe)){
if ((Pe[j])>0) {
k[j]<-Pe[j]
}
}
The lenght of the vector Pe
is 1000. I need only to save the values mayor than zero in the vector k, but when I type the vector k the display window show:
numerical(0)
This is the correct way to initiate a empty vector in R (k)?
Thanks
in fact, it can be much more easy. Type
k <- c()
instead. But I think this won't get you what you want.
What happens when element p is not > 0? R will fill k[p] with NA, while I think you want k to be a shorter vector of only the elements of Pe which are > 0, not to be the same length but with NA's?
If so, you don't even need a loop. Try
k <- Pe[Pe > 0]
This will get you a vector only containing the elements of Pe > 0, no NA's.
Excuse my bad english, hope I helped you
As MaxPD pointed out
for (j in length(Pe)) print(j)
would only print the length of Pe, you should
for (j in seq_len(length(Pe))) print(j)
## or
for (j in seq_along(Pe)) print(j)
## or
for (j in 1:length(Pe)) print(j)
but in your case i wouldn't even use a loop
k<-vector(mode = "numeric", length = 0)
k[Pe > 0] <- Pe[Pe > 0]
should do the trick if both objects are vectors and have the same length.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.