How to create one vector from another in r?

Asked

Viewed 114 times

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 didn’t work. The str_detect finds only strings. Has some function as contained or other way to do this?

2 answers

6


Another way is with the function is.na<-. And to create the vector fixo used the function numeric, more the idea by Willian Vieira to obtain 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
  • excellent, very elegant.

5

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

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
  • excellent, very elegant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.