Reputation: 335
I have a dataset (df) looks like this.
A B C D E Position
67 68 69 70 71 5
20 21 22 23 24 2
98 97 96 95 94 3
2 5 7 9 12 5
4 8 12 16 20 4
I am trying to create a new column (Result
) where the value of result is equal to the position of the column specified in the position
column for each row of the resulting column.
For example, if the row 1 of position
column is 5, the Result
column will have the value of 5th column of row 1.
My resulting column will look like this:
A B C D E Position Result
67 68 69 70 71 5 71
20 21 22 23 24 2 21
98 97 96 95 94 3 96
2 5 7 9 12 5 12
4 8 12 16 20 4 16
I used the following command, which does not give me what I need. It lumps all of the position
column values in each row. I am unable to determine how I can get the correct result.
Any help is appreciated.
Thanks!
Upvotes: 1
Views: 147
Reputation: 193687
Use matrix indexing to extract the values:
df[cbind(1:nrow(df), df$Position)]
# [1] 71 21 96 12 16
Assign the result in the normal way:
df$Result <- df[cbind(1:nrow(df), df$Position)]
Upvotes: 2