francoiskroll
francoiskroll

Reputation: 1098

R - How can I insert/shift a value in a specific row?

I want to insert a value (actually a "NA") in a specific row at a specific column in a matrix. I would like the rest of the row (the subsequent columns) to shift by one as a consequence of the insertion. No values should be deleted in the process, I want to insert a value, not replace one.

Example

My input matrix looks like:

1 2 3 4 NA
1 2 3 4 NA
1 2 3 4 NA

Something like:

insertShift (insert = NA, where = df[2, 3])

Output matrix should look like:

1 2 3 4 NA
1 2 NA 3 4
1 2 3 4 NA

Upvotes: 0

Views: 262

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

Something like this would work... mat[2,3:ncol(mat)] <- c(NA,mat[2,3:(ncol(mat)-1)])

Upvotes: 1

Related Questions