/ / Duplicando um quadro de dados e substituindo valores - r, dataframe, dplyr, plyr, gsub

Duplicando um quadro de dados e substituindo valores - r, dataframe, dplyr, plyr, gsub

Se eu tiver dois quadros de dados:

Df1:
Name1 Name2 Destination1
A     I       London
B     J       Paris
C     K       New York
D     L       Bangkok
E     M       Singapore

Df2:
Theme      Pattern
Luxury      luxury hotels in {d}
City        city hotels {d}
Break        breaks in {d}
Package      {d} packages

Essencialmente, eu quero um novo quadro de dados em que para cada destination1 em Df1 eu tenho todos os padrões de Df2, mantendo a coluna Theme e ambas as colunas Name 1 Name 2 do Df1.

Por exemplo. Saída desejada:

Df3:
Name 1      Name 2     Destination 1  Theme     Pattern
A            I            London      Luxury     luxury hotels in {London}
A            I            London      City       city hotels {London}
A            I            London      Break       breaks in {London}
A            I            London      Packages    {London} packages
B            J            Paris       Luxury       luxury hotels in {Paris}
B            J            Paris       City         city hotels {Paris}
B            J            Paris       Break        breaks in {Paris}
B            J            Paris       Packages     {Paris} packages
C etc....

Respostas:

1 para resposta № 1

Você pode usar a solução dplyr e tidyr para isso: Primeiro, remodele o Df2 para o formato amplo e o cbind com Df1; em seguida, junte-se ao formato longo original. Em seguida, usando o gsub com expressão regular, substitua {d} pelo destino.

library(dplyr)
library(tidyr)

Df1 <- data.frame(name1 = LETTERS[1:5],
name2 = LETTERS[9:13],
Destination1 = c("London", "Paris", "New York", "Bangkok", "Singapore")
)

Df2 <- data.frame(Theme = c("Luxury", "City", "Break", "Package"),
Pattern = c("Luxury hotels in {d}",
"City hotels in {d}",
"Breaks in {d}",
"{d} packages")
)

Df3 <- Df1 %>%
# reshape Df2 to wide format and combine it with Df1
cbind(spread(data = Df2, key = Theme, value = Pattern)) %>%
# convert back to long format
gather(key = Theme, value = Pattern, Break:Package) %>%
# replace {d} with Destination
mutate(Pattern = gsub(pattern = "\{d\}",
replacement = Destination1,
x = Pattern))

0 para resposta № 2

Não exatamente os mesmos dados (você deve fornecer o código para gerar os dados), mas isso faz as coisas que você está procurando! Embora não seja muito elegante, devo admitir ...

A=data.frame(c1=c("A", "B", "C"), c2=c("london", "paris", "berlin"))
B=data.frame(c3=c("a", "b", "c"), c4=c("la{d}", "{d}lala", "lala{d}la"))
# aggregate the df
AB <- data.frame(c1=rep(A$c1, nrow(B)), c2=rep(A$c2, nrow(B)),
c3=rep(B$c3, each=nrow(A)), c4=rep(B$c4, each=nrow(A)))
# change {d} in city names
AB$c4 <- sapply(1:nrow(AB), function(x) gsub("\{d\}",
paste(" ", AB[x,"c2"], " "), AB[x,"c4"]))
# regroup by city names
AB <- AB[order(AB$c2),]
AB # enjoy

0 para resposta № 3

você pode criar uma nova variável para cada conjunto de dados e depois removê-la após a junção. Você pode fazer abaixo.

library(dplyr)
Df1$new <- "lol"

Df2$new <- "lol"

Df3 <- full_join(Df1,Df2) %>% select(-new)


**example:
df1 <- data.frame(a=c(1:5),b=c(7:11))

df2 <- data.frame(c=c(12:16),d=c(17:21))

df1$new <- "lol"
df2$new <- "lol"
library(dplyr)

full_join(df1,df2) %>% select(-new)**