如何根据出现顺序替换唯一的向量元素?

问题描述 投票:0回答:2

假设我有这个 df(但大得多)

df = data.frame(x = rep(1:10,each=2) )

我希望这个数据框变成如下(目标是我不想用它的同源物替换每个值。我想找到一种方法用它们可用的同源物替换所有这 10 个值。)

df = data.frame(x = rep(c(10,88,56,41,19,35,41,26,17,61),each=2))

    x
1  10
2  10
3  88
4  88
5  56
6  56
7  41
8  41
9  19
10 19
11 35
12 35
13 41
14 41
15 26
16 26
17 17
18 17
19 61
20 61
r dataframe replace numeric
2个回答
2
投票

match
(这不依赖于
df$x
首先是
1:10
的事实):

lookup = setNames(c(10,88,56,41,19,35,41,26,17,61), unique(df$x))
df$x <- lookup[match(df$x, names(lookup))]
# [1] 10 10 88 88 56 56 41 41 19 19 35 35 41 41 26 26 17 17 61 61

2
投票

这就是你想要做的吗?不确定我是否理解“同系物”的意思。

homologues <- c(10,88,56,41,19,35,41,26,17,61)
df$x <- homologues[df$x]

或者可能:

names(homologues) <- unique(df$x)
df$x <- homologues[as.character(df$x)]

两种情况下的结果:

    x
1  10
2  10
3  88
4  88
5  56
6  56
7  41
8  41
9  19
10 19
11 35
12 35
13 41
14 41
15 26
16 26
17 17
18 17
19 61
20 61
© www.soinside.com 2019 - 2024. All rights reserved.