如何为R中的向量或数据帧中的每个元素返回索引?

时间:2018-07-21 16:21:50

标签: r dataframe vector indexing

当我尝试研究这个问题时,我发现了许多对which()函数的引用。我无法适应当前的需求。我希望以下内容可以说明我正在尝试做的事情以及原因:

test <- c("c","b","a","e","d")
test <- as.data.frame(test)
colnames(test) <- "code"
# How can I return the index for each item in the vector?
# test$indx <- ?

# Desired outcome
#     code  index
# 1    c     1
# 2    b     2
# 3    a     3
# 4    e     4
# 5    e     5

# hard-coding desired output to illustrate why I want it
test$index <- seq(from = 1, to = 5, by = 1)

library(dplyr)
test <- arrange(test, code)
test
#   code index
# 1    a     3
# 2    b     2
# 3    c     1
# 4    d     5
# 5    e     4

1 个答案:

答案 0 :(得分:1)

这是

test <- c("c","b","a","e","d")
test <- as.data.frame(test)
colnames(test) <- "code"
test$index <- 1:nrow(test)
test

library(dplyr)
test <- arrange(test, code)
test