royer
royer

Reputation: 645

how to change the values of a vector using index?

I speak of indexes referring to the order as R stores each value. Now I only want to edit values of an object but on the condition that its index is odd numbers (1 3 5 7 9 ..)

b[index]

have the following variables

a <- c("a","b","c","d") # 4 values
b <- rep(NaN,length(a)*2 ) # 8 values

now in vector b I have 8 data and my goal is to change the values in an odd way:

> b[1]
[1] "a"

> b[5]
[1] "c"

> b[2]
[1] NaN

> b[6]
[1] NaN

> b[3]
[1] "b"

>  b[7]
[1] "d"

> b[4]
[1] NaN

> b[8]
[1] NaN

Is there any automatic way to do this process? example for(i in(1:length(b)))

b[2*(1:length(a))- 1 ] = a

error only 0's can be mixed with negative subscriptions

Upvotes: 1

Views: 713

Answers (3)

tmfmnk
tmfmnk

Reputation: 40181

Yet another option could be:

b[seq_along(b) %% 2 == 1] <- a

[1] "a"   "NaN" "b"   "NaN" "c"   "NaN" "d"   "NaN"

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 146249

a <- c("a","b","c","d")
# use the right data type
b <- rep(NA_character_,length(a)*2 )

# generate odd numbers
seq(from = 1, length.out = length(a), by = 2)
# [1] 1 3 5 7

#  do replacement
b[seq(from = 1, length.out = length(a), by = 2)] = a

b
# [1] "a" NA  "b" NA  "c" NA  "d" NA 

Your code for the sequence works as well. No loops necessary:

b[2*(1:length(a))- 1 ] = a

Upvotes: 1

akrun
akrun

Reputation: 887991

We can use a recycling index with logical index

b[c(TRUE, FALSE)] <- a
b
#[1] "a"   "NaN" "b"   "NaN" "c"   "NaN" "d"   "NaN"

Upvotes: 1

Related Questions