简体   繁体   中英

R-Creating a New Column Based On Positions Specified by an Existing Column

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!

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM