Reputation: 21
I got stuck while trying to get my data into the correct output format. The original data consists of a table with two columns: (1) groupname (2) mailadress, e.g.
groupname mailadress
group1 [email protected]
group1 [email protected]
group2 [email protected]
group2 [email protected]
But I need the data in the following format and saved as a text file:
# group1
[email protected]
dummy2@hotmail
# group2
[email protected]
[email protected]
I know there must be a way to achieve this using dplyr
, e.g. group_walk()
, but I've currently run out of ideas... Can anybody give me a hint?
Upvotes: 1
Views: 87
Reputation: 316
not sure if i got what you want
x<-df%>%filter(groupname =="group1")%>%select(mailadress)
names(x)<-"group1"
write.table(x, file = "X.txt", sep = "\t",
row.names = FALSE)
but this wil output
"group1"
"[email protected]"
"[email protected]"
if its not the point tell me better so i can help
Upvotes: 0
Reputation: 21
Okay, so I found one possible solution. Say the data.frame
is df
:
export <- df %>% select(groupname, mailadress) %>% group_by(groupname) %>%
+ mutate(mails = paste0(mailadress, collapse = "\n")) %>% slice(1) %>% select(groupname, mails)
export$groupname<- paste0("# ",export$groupname)
write.table(export, "export.txt", sep = "\n", row.names = F, col.names = F, quote = F)
Upvotes: 1
Reputation: 3047
library(tidyverse)
df <- tribble(
~groupname, ~mailadress,
"group1", "[email protected]",
"group1", "[email protected]",
"group2", "[email protected]",
"group2", "[email protected]"
)
df %>%
split(df$groupname) %>%
map(
~paste0("# ", .x$groupname[1], "\n", paste(.x$mailadress, collapse = "\n"))
) %>%
unlist() %>%
paste(collapse = "\n\n") %>%
cat(file = "output.txt")
Upvotes: 0