Take value from nth column of a data frame, for n

2020-07-23 08:40发布

How do I construct a vector of values from nth column of some data frame, where n is a per-row value defined in some vector? Example:

> df <- data.frame(a=c(100, 110, 120, 130, 140),
                   b=c(200, 210, 220, 230, 240),
                   c=c(300, 310, 320, 330, 340))
> df
    a   b   c
1 100 200 300
2 110 210 310
3 120 220 320
4 130 230 330
5 140 240 340
> cl <- c(1, 3, 3, 2, 1)
> some.function(df, cl)

would result in:

[1] 100 310 320 230 140

1条回答
虎瘦雄心在
2楼-- · 2020-07-23 09:33

You can index by a 2-column matrix -- the first column is the row number and the second is the column number.

df[cbind(seq(cl), cl)]
# [1] 100 310 320 230 140

This is a vectorized operation that should be quicker than looping through the rows with something like sapply and grabbing the appropriate value from that row:

# Slightly larger example, with 1000 rows
set.seed(144)
df <- matrix(rnorm(3000), nrow=1000)
cl <- sample(3, 1000, replace=TRUE)
all.equal(df[cbind(seq(cl), cl)], sapply(seq(nrow(df)), function(i) df[i, cl[i]]))
# [1] TRUE
library(microbenchmark)
microbenchmark(df[cbind(seq(cl), cl)], sapply(seq(nrow(df)), function(i) df[i, cl[i]]))
# Unit: microseconds
#                                             expr     min      lq       mean   median
#                           df[cbind(seq(cl), cl)]  23.828  26.335   34.26012  30.0350
#  sapply(seq(nrow(df)), function(i) df[i, cl[i]]) 855.481 922.449 1178.47502 996.3815
#         uq      max neval
#    38.0315  135.894   100
#  1111.3960 3414.374   100
查看更多
登录 后发表回答