【发布时间】:2018-09-29 21:03:24
【问题描述】:
今天这给我带来了很多麻烦,我确信有一个我没有想到的明显解决方案。
我有一个几千行的数据框。有一列,该列中的每个值恰好出现两次。我想找到每个匹配值的索引。该列如下所示:
col
1 cat
2 dog
3 bird
4 dog
5 bird
6 cat
我想知道匹配出现的相应索引,所以它会返回如下内容:
[1] 6 4 5 2 3 1
【问题讨论】:
今天这给我带来了很多麻烦,我确信有一个我没有想到的明显解决方案。
我有一个几千行的数据框。有一列,该列中的每个值恰好出现两次。我想找到每个匹配值的索引。该列如下所示:
col
1 cat
2 dog
3 bird
4 dog
5 bird
6 cat
我想知道匹配出现的相应索引,所以它会返回如下内容:
[1] 6 4 5 2 3 1
【问题讨论】:
我们可以的
df$new_col <- seq_along(df$col)
df$new_col <- with(df, ave(new_col, col, FUN = rev))
df
# col new_col
#1 cat 6
#2 dog 4
#3 bird 5
#4 dog 2
#5 bird 3
#6 cat 1
在第一步中,我们创建一个 new_col 作为从 1 到 nrow(df) 的序列。所以这个变量和行号没有区别。
如果我们将变量col 视为定义组,如果我们reverse 以col 为一组新创建的列以获得所需的输出,我们将获得“匹配出现的相应索引”。
作为单行者
with(df, ave(seq_along(col), col, FUN = rev))
数据
df <- structure(list(col = c("cat", "dog", "bird", "dog", "bird", "cat"
)), .Names = "col", class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
【讨论】: