根据模板多次替换值

And*_*ico 7 r

为了对长数据进行GROUP VARIABLE,我想将多个值组合成一个新值.

我已经有一个解决方案,但我觉得可以有更好的实现.

set.seed(1337)
df <- data.frame(coli = sample(rep(1:6,2)), newi = 0 )

replaceList <- list(oneAndTwo=1:2, threeAndFour=3:4, fiveAndSix=5:6)
Run Code Online (Sandbox Code Playgroud)

数据看起来像:

> df
   coli newi
1     1    0
2     6    0
3     1    0
4     5    0
5     3    0
6     2    0
7     6    0
8     2    0
9     4    0
10    4    0
11    3    0
12    5    0
Run Code Online (Sandbox Code Playgroud)

查找模板看起来像:

> replaceList
$oneAndTwo
[1] 1 2

$threeAndFour
[1] 3 4

$fiveAndSix
[1] 5 6
Run Code Online (Sandbox Code Playgroud)

期望的结果:

   coli         newi
1     1    oneAndTwo
2     6   fiveAndSix
3     1    oneAndTwo
4     5   fiveAndSix
5     3 threeAndFour
6     2    oneAndTwo
7     6   fiveAndSix
8     2    oneAndTwo
9     4 threeAndFour
10    4 threeAndFour
11    3 threeAndFour
12    5   fiveAndSix 
Run Code Online (Sandbox Code Playgroud)

我的工作尝试

mapply(function(fnd,rplc){IND=df$coli %in% fnd;df$newi[IND]<<-rplc},fnd=replaceList,rplc=names(replaceList))
Run Code Online (Sandbox Code Playgroud)

如果有更好的练习,也就如何设置replaceList我很乐意学习.

你会如何解决/解决这样的问题?

akr*_*run 5

我们可以stacklist一个键/值数据集("DF2"),然后做一个match与"DF2"的"价值"列以获取"IND"对应的索引并指定为'的"东风"的"菌"之间newi"

df2 <- stack(replaceList)
df$newi <- df2$ind[match(df$coli, df2$values)]
df
#   coli         newi
#1     4 threeAndFour
#2     3 threeAndFour
#3     6   fiveAndSix
#4     1    oneAndTwo
#5     2    oneAndTwo
#6     1    oneAndTwo
#7     5   fiveAndSix
#8     2    oneAndTwo
#9     4 threeAndFour
#10    6   fiveAndSix
#11    3 threeAndFour
#12    5   fiveAndSix
Run Code Online (Sandbox Code Playgroud)