HeinKK
HeinKK

Reputation: 75

How can I fill a vector by matrix column in R?

Assume I have following matrix:

mat <- matrix(0L,61,5)
mat[,1] <- seq(0.7,60.7,1)
mat[,2] <- seq(0.5,60.5,1)
mat[,3] <- seq(0.4,60.4,1)
mat[,4] <- seq(0.1,60.1,1)
mat[,5] <- seq(0.9,60.9,1)

And following Vectors:

Vec1: 0   0   0   0   0  20   0   0   0   0   0   0   0  20   0   0   0   0   0   0  20 120   0
Vec2: 0   0   0   0   0   0   0  20   0   0   0   0   0  20   0   0   0   0   0   0  20   0 120
Vec3: 0   0   0   0   0   0   0  20   0   0  20   0   0   0  20 120   0   0   0   0   0   0   0
...

Now I would like to fill the Vectors with the matrix value (mat[,1] -> vec1) if the vector isn't zero. For simplicity its an example, so things like that don't work, because i don't know the distance between the values and the frequency of zero. However, this should be the solution for Vector 1:

Vec1 <- c(rep(0,5),mat[1,1],rep(0,7),mat[2,1],rep(0,6),mat[3,1],mat[4,1],0)
> Vec1 0.0 0.0 0.0 0.0 0.0 0.7 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.7 0.0 0.0 0.0 0.0 0.0 0.0 2.7 3.7 0.0

Upvotes: 0

Views: 110

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24770

Here's an approach with mget and lapply from base R:

veclist <- mget(ls(pattern = "Vec[0-9]+"))

lapply(names(veclist),function(x){
  ind <- as.integer(gsub(".*([0-9]+)","\\1",x))
  result <- veclist[[x]]
  toreplace <- which(result != 0)
  result[toreplace] <- mat[seq_along(toreplace),ind]
  result})
[[1]]
 [1] 0.0 0.0 0.0 0.0 0.0 0.7 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.7 0.0 0.0 0.0 0.0 0.0 0.0 2.7 3.7 0.0

[[2]]
 [1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 0.0 1.5 0.0 0.0 0.0 0.0 0.0 0.0 2.5 0.0 3.5

[[3]]
 [1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.4 0.0 0.0 1.4 0.0 0.0 0.0 2.4 3.4 0.0 0.0 0.0 0.0 0.0 0.0 0.0

Sample Data

Vec1 <- c(0L, 0L, 0L, 0L, 0L, 20L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 
0L, 0L, 0L, 0L, 0L, 20L, 120L, 0L)
Vec2 <- c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 
0L, 0L, 0L, 0L, 0L, 20L, 0L, 120L)
Vec3 <- c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 0L, 20L, 0L, 0L, 0L, 20L, 
120L, 0L, 0L, 0L, 0L, 0L, 0L, 0L)

Upvotes: 1

Related Questions