R中的匹配和返回列表

R中的匹配和返回列表,r,match,vlookup,R,Match,Vlookup,我有一个数据框,它有两列owner和user,两个字符串,两个名称。每一行代表一种关系。所有者在论坛上发布了一个问题,用户已重播。当特定用户成为所有者时,我需要所有用户的列表。重复项是可以的,列表必须与它相同,因为存在时间变量 | Owner | User | |-------|------| | A | B | | A | C | | B | V | | B | D | | C | A | 输出将是每

我有一个数据框,它有两列owner和user,两个字符串,两个名称。每一行代表一种关系。所有者在论坛上发布了一个问题,用户已重播。当特定用户成为所有者时,我需要所有用户的列表。重复项是可以的,列表必须与它相同,因为存在时间变量

| Owner | User |   
|-------|------|  
| A     | B    |  
| A     | C    |  
| B     | V    | 
| B     | D    | 
| C     | A    |
输出将是每行的新字符串-列输出,并且在该输出分类之后。我可以自己做

| Owner | User | Output | Cat_output |  
|-------|------|--------|------------|  
| A     | B    | V,D    | indirect   |  
| A     | C    | A      | direct     |  
| B     | V    |        | empty      |  
| B     | D    |        | empty      |  
| C     | A    | B,C    | direct     | 
我会用Excel返回这个

我必须在R中复制这个,但我想不出来

谢谢
Primoz

我们可以使用
sapply
检查
所有者
列中存在
用户
的行,并选择相应的值

df$Output <- sapply(df$User, function(x) df$User[df$Owner %in% x])

df
#  Owner User Output
#1     A    B   V, D
#2     A    C      A
#3     B    V       
#4     B    D       
#5     C    A   B, C

df$Output您可以使用
dplyr
中的
groupby()
summary()
函数

library(dplyr)

df <- data.frame(owner = c("A", "A", "B", "B", "C"),
             user  = c("B", "C", "V", "D", "A"),
             stringsAsFactors = FALSE
             )
out <- group_by(df, owner) %>% summarize(output = list(user))
left_join(df, out, by = c("user" = "owner"))

# owner user output
# 1     A    B   V, D
# 2     A    C      A
# 3     B    V   NULL
# 4     B    D   NULL
# 5     C    A   B, C# 
库(dplyr)

df按照与其他人类似的思路,
split
浮现在脑海中

作为
列表的“输出”:

df$Output <- with(df, split(User, Owner))[df$User]
df
#   Owner User Output
# 1     A    B   V, D
# 2     A    C      A
# 3     B    V   NULL
# 4     B    D   NULL
# 5     C    A   B, C

df$Output最后我使用了这个单字符串解决方案。
df$Output <- sapply(with(df, split(User, Owner)), toString)[df$User]
df
#   Owner User Output
# 1     A    B   V, D
# 2     A    C      A
# 3     B    V   <NA>
# 4     B    D   <NA>
# 5     C    A   B, C