介于1-8之间的任何玩家称为“前进”,介于9-15之间的任何玩家称为“后退”,但这些玩家可以替换为数字大于15的其他玩家,并且该新玩家应保持相同的状态(前进或后退) 。因此,如何通过引用分配此状态编码?例子
data.frame(Player_substituted=c(7, 15, 2, 1, 8, 5, 22, 18),
Player_substitute=c(22, 18, 16, 17, 20, 19, 21, 23)
)
#Table
Player_substituted Player_substitute
7 22
15 18
2 16
1 17
8 20
5 19
22 21
18 23
这个想法是要有一个类似
的输出: Player_substituted Player_substitute status_P_sustituted
7 22 Forward
15 18 Backward
2 16 Forward
1 17 Forward
8 20 Forward
5 19 Forward
22 21 Forward
18 23 Backward
例如,这意味着玩家7为“前进”,并且他被玩家22替代,因此玩家22也为“前进”。但是,玩家15是“后退”,他被玩家18取代,因此玩家18也是“后退”
一个选择是使用功能which()来识别索引(这只是草稿)
#To find index of user with number higher than 15
Index<-which(!Player_substituted%in%1:15)
#To find the user susituted
Index_2<-which(Player_substitute==Player_substituted[Index])
....
可以肯定,这不是最有效的方法。另外,我需要按其他变量进行分组。有什么建议吗?
非常感谢!
答案 0 :(得分:1)
基本上,您想构建一个替换链,并根据链中的第一个玩家为链成员分配一个值。我们可以利用igraph
包来构建替换链,以便为以后的替换分配正确的值。
library(igraph)
library(dplyr)
df <- data.frame(Player_substituted=c(7, 15, 2, 1, 8, 5, 22, 18),
Player_substitute=c(22, 18, 16, 17, 20, 19, 21, 23))
# Generate edges for igraph
edges <- as.character(as.vector(t(df)))
# Generate igraph object
g <- graph(edges)
# Get cluster membership
memb <- clusters(g)$membership
data.frame(Player_substitute = as.numeric(names(memb)), group_id = memb) %>%
group_by(group_id) %>%
mutate(status_P_substituted = if_else(first(Player_substitute) < 9, "Forward", "Backward")) %>%
ungroup() %>%
right_join(df, by = "Player_substitute") %>%
select(Player_substituted, Player_substitute, status_P_substituted)
Player_substituted Player_substitute status_P_substituted
<dbl> <dbl> <chr>
1 7 22 Forward
2 15 18 Backward
3 2 16 Forward
4 1 17 Forward
5 8 20 Forward
6 5 19 Forward
7 22 21 Forward
8 18 23 Backward
答案 1 :(得分:0)
您必须保存数据框的对象:
dat<-data.frame(Player_substituted=c(7, 15, 2, 1, 8, 5, 22, 18)
Player_substitute=c(22, 18, 16, 17, 20, 19, 21, 23))
现在您可以在新列中输入值了
dat$Player_Substitued<-ifelse(dat$Player_substituted < 9, "Forward", "Backward")
使用“ $”可以在对象中添加新列