我有我的桌子(输入):
user_name event_id
1 "Joe" Source:Coins:MinigameReward
2 "Tom" Sink:Coins:EndSession
3 "Fred" Sink:Tickets:StartGame
4 "Tom" Source:Tickets:EndSession
5 "Joe" Sink:Coins:EndSession
我想在字段Source:Coins
中只保留包含Sink:Coins
或event_id
的行。结果(输出):
user_name event_id
1 "Joe" Source:Coins:MinigameReward
2 "Tom" Sink:Coins:EndSession
3 "Joe" Sink:Coins:EndSession
event_id
是角色。
答案 0 :(得分:2)
df <- data.frame(user_name=c('Joe','Tom','Fred','Tom','Joe'),event_id=c('Source:Coins:MinigameReward','Sink:Coins:EndSession','Sink:Tickets:StartGame','Source:Tickets:EndSession','Sink:Coins:EndSession'),stringsAsFactors=F);
df[grep('(Source|Sink):Coins',df$event_id),];
## user_name event_id
## 1 Joe Source:Coins:MinigameReward
## 2 Tom Sink:Coins:EndSession
## 5 Joe Sink:Coins:EndSession
答案 1 :(得分:1)
不确定输入的格式是什么,但对于数据框,您可以使用grep查找匹配字符串的索引。
df=data.frame(user_name = c("Joe" ,"Tom" ,"Fred" ,"Tom" ,"Joe"),"event_id"=c("Source:Coins:MinigameReward","Sink:Coins:EndSession","Sink:Tickets:StartGame","Source:Tickets:EndSession","Sink:Coins:EndSession"))
df[c(grep("Source:Coins",df$event_id), grep("Sink:Coins",df$event_id)),]