Assign the half of the vector in R

Viewed 312

I want to assign the half of the vector 1 and the rest o

df <- c("1","a","b","2")
[1] "1" "a" "b" "2"

Expected result

 [1] "1" "1" "0" "0"

many thanks in advance

2 Answers

Using rep

rep(1:0, each = length(df)/2, length.out = length(df))
#[1] 1 1 0 0

If it doesn't matter how 1's and 0's are assigned you could specify only length.out

rep(1:0, length.out = length(df))
#[1] 1 0 1 0

Also, slightly different way, would be:

'<-'(df, +(seq_along(df) <= length(df) %/% 2))
#df
#[1] 1 1 0 0
Related