# 从数据帧的第n列获取值，每行n个值不同Take value from nth column of a data frame, for n different for each row

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

``````[1] 100 310 320 230 140
``````

## 1 个回复1

### ===============>>#1 票数：3 已采纳

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

``````# 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
``````

1回复

2回复

4回复

3回复

1回复

1回复

1回复

3回复

2回复

3回复