Compliance and Return List in R

I have a data frame with two owners and user columns, both rows, both names. Each row represents a relationship. The owner submitted the question to the forum and the user replayed. I need a list of all users when the user becomes the owner. Duplicates are fine, the list should be the same as with a time variable.

| Owner | User |   
|-------|------|  
| A     | B    |  
| A     | C    |  
| B     | V    | 
| B     | D    | 
| C     | A    |

The output will be a new row column "Output" for each row and after this categorization of this output. I can do the categorization myself.

| 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     | 

I would return this to Excel using Returns the MULTIPLE corresponding values ​​for the ONE Lookup Value, horizontally, in the same row .

I have to reproduce this in R and cannot understand.

Thanks Primoz

+4
3

, , split ...

"" list:

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 <- 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
0

sapply , , a User Owner, .

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
+2

group_by() summarize() dplyr.

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# 
0

Source: https://habr.com/ru/post/1670394/


All Articles