简体   繁体   中英

Create New Variable from Column Index Value

My goal is to create a new variable that contains the value indicated by a column index.

c <- rep(1:2)
d <- rep(1:10)
e <- c(1,5,7,2,3,9,1,6,9,1)
z <- cbind(d,e,c)

I would like to create a new variable (f) that is the value indicated by the column index of c.

d   e   c   f
1   1   1   1
2   5   2   5
3   7   1   3
4   2   2   2
5   3   1   5
6   9   2   9
7   1   1   7
8   6   2   6
9   9   1   9
10  1   2   1

We can use row/column indexing to extract the elements from the first 2 columns of 'z', where the row index is the sequence of rows and column index is 'c' column from the matrix 'z'

cbind(z, f = z[,1:2][cbind(seq_len(nrow(z)), z[,"c"])])
#       d e c f
# [1,]  1 1 1 1
# [2,]  2 5 2 5
# [3,]  3 7 1 3
# [4,]  4 2 2 2
# [5,]  5 3 1 5
# [6,]  6 9 2 9
# [7,]  7 1 1 7
# [8,]  8 6 2 6
# [9,]  9 9 1 9
#[10,] 10 1 2 1

An option could be use mapply to get desired output.

cbind(z, f = mapply(function(x,y)z[y,x], z[,"c"], 1:nrow(z)))
#    d e c f
# d  1 1 1 1
# e  2 5 2 5
# d  3 7 1 3
# e  4 2 2 2
# d  5 3 1 5
# e  6 9 2 9
# d  7 1 1 7
# e  8 6 2 6
# d  9 9 1 9
# e 10 1 2 1

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