How to Declare a Vector of Zeros in R

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

Create a Vector of Length N of the same numbers in R

rep(4.5, 100)

The function rep does the trick

Adding zeros in front of an vector

Something like this?

# create a vector
a <- rnorm(730)
# add the 0
a <- c(rep(0,730), a)

Then you could make a matrix:

m <- cbind(1:length(a), a)

Change zero to ones in vector if surrounded by less than five consecutive zeros

A possible solution with rle which does not change shorts sequences of zero's at the beginning or end of x:

# create the run length encoding
r <- rle(x)

# create an index of which zero's should be changed
i <- r$values == 0 & r$lengths < 5 &
c(tail(r$values, -1) == 1, FALSE) &
c(FALSE, head(r$values, -1) == 1)

# set the appropriate values to 1
r$values[i] <- 1

# use the inverse of rle to recreate the vector
inverse.rle(r)

which gives:

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

Sum elements of a vector beween zeros in R

We can use tapply, creating groups with cumsum and take sum of each group.

new_x <- tapply(x, cumsum(x == 0), sum)
new_x

# 1 2 3 4 5 6 7 8 9 10
# 0 0 0 0 138 0 0 0 156 14

Since all numbers are positive we can ignore the ones with 0 and filter the one which has value greater than 0.

new_x[new_x > 0]
# 5 9 10
#138 156 14

We can also follow the same logic with sapply and split

sapply(split(x, cumsum(x==0)), sum)

Create a matrix of zeros and ones from R

We can use model.matrix in base R

model.matrix(~ factor(id) - 1, data_toy)

-output

#   factor(id)1 factor(id)2 factor(id)3
#1 1 0 0
#2 1 0 0
#3 1 0 0
#4 0 1 0
#5 0 1 0
#6 0 0 1

Or use table

with(data_toy, table(seq_along(id), id))

How to define blocks of elements in a vector to zero and looping over the next blocks?

First, I define my vector and matrix.

# Data definitions
a <- c(1:6)
b <- matrix(1:36, nrow = 6, ncol = 6)

Next, I create a function that produces a list of your a values. It defaults to blocks of zeros that are length two.

# Define blocks of zeroes in vector 
define_block <- function(v, n = 2){
# Check that v is a multiple of n
if(length(v)%%n)warning("Vector not a multiple of block length")

# Define blocks of zeroes
lapply(1:(length(v)/n), function(x)replace(v, ((x-1)*n + 1):(x*n), 0))
}

Here, I apply the function:

# Create lists of blocks
block_list <- define_block(a)

which produces,

# [[1]]
# [1] 0 0 3 4 5 6
#
# [[2]]
# [1] 1 2 0 0 5 6
#
# [[3]]
# [1] 1 2 3 4 0 0

Finally, I run through block_list and perform your calculation and bind the results together using do.call with rbind.

# Run through block list and bind result into a matrix
do.call(rbind, lapply(block_list, function(x)x%*%b))


# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 86 194 302 410 518 626
#[2,] 66 150 234 318 402 486
#[3,] 30 90 150 210 270 330


Related Topics



Leave a reply



Submit