R中的表与字段中的特定字符串排序(r语言)

时间:2016-04-25 13:50:17

标签: r

我有我的桌子(输入):

     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:Coinsevent_id的行。结果(输出):

     user_name    event_id  
1     "Joe"    Source:Coins:MinigameReward
2     "Tom"    Sink:Coins:EndSession
3     "Joe"    Sink:Coins:EndSession

event_id是角色。

2 个答案:

答案 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)),]