How to create a vector from another in r?

3

I need to create the vector fixo of NA and 0 from another vector coef . If

coef<-c(1,4,10)

then

fixo = (NA,0,0,NA,0,0,0,0,0,NA)

I tried to use str_detect :

num<-c(1,4,10)
maiorn <- max(num)
A<-seq(1:maiorn)

for (i in 1:maiorn) {
  ifelse(str_detect(A[i], num),
         A[i]<-"NA",
         A[i]<-0)
}

But it did not work. str_detect only finds strings. Do you have any function as contained or any other way to do this?

    
asked by anonymous 13.12.2018 / 20:50

2 answers

5

Another way is with the function is.na<- . And to create the vector fixo I used the function numeric , plus a # to get the length of fixo with max(coef) .

coef <- c(1, 4, 10)
fixo <- numeric(max(coef))

is.na(fixo) <- coef

fixo
#[1] NA  0  0 NA  0  0  0  0  0 NA
    
13.12.2018 / 23:14
4

You can use the coef vector to index the elements of the fixo vector:

coef <- c(1,4,10)

# criar vetor de zeros
fixo <- rep(0, max(coef))

# adicionar NA para cada coef
fixo[coef] <- NA

fixo
# [1] NA  0  0 NA  0  0  0  0  0 NA
    
13.12.2018 / 21:27