让我们假设我的数据框如下:
col1 col2 col3 what_col
1 1 2 5 1
2 4 1 2 2
3 3 1 8 2
4 1 5 3 1
5 4 4 1 3
...
我需要创建vector:
1 1 1 1 1 .....
(在 what_col 中存储了每行所需的列)
答案 0 :(得分:1)
你可以尝试
df[cbind(1:nrow(df), df$what_col)]
#[1] 1 1 1 1 1
df <- structure(list(col1 = c(1L, 4L, 3L, 1L, 4L), col2 = c(2L, 1L,
1L, 5L, 4L), col3 = c(5L, 2L, 8L, 3L, 1L), what_col = c(1L, 2L,
2L, 1L, 3L)), .Names = c("col1", "col2", "col3", "what_col"),
class = "data.frame", row.names = c("1", "2", "3", "4", "5"))
答案 1 :(得分:1)
这是另一个选择
df[col(df) == df$what_col]
## [1] 1 1 1 1 1