Reputation: 41
My df looks like this:
x a b c d e
0 0 0 1 1 1
1 0 0 1 1 1
2 0 0 1 1 1
I would like to horizontally shift each row based on the value in the x column, so that the new df looks like this:
a b c
0 0 1
0 1 1
1 1 1
Have been able to find examples of horizontal shifts to replace na, but not a shift based on a value like this - so any help greatly appreciated.
Thanks!
Upvotes: 0
Views: 149
Reputation: 12819
Apply the shift horizontally (MARGIN = 1
) and transpose with t()
t(apply(df, 1, function(row) row[2:4 + row[["x"]]]))
#> [,1] [,2] [,3]
#> [1,] 0 0 1
#> [2,] 0 1 1
#> [3,] 1 1 1
data:
df <- data.frame(
x = 0:2,
a = 0, b = 0,
c = 1, d = 1, e = 1
)
Upvotes: 2