left_join in a for loop with different columns names

Viewed 773

I have a data.frame called a whose structure is similar to:-

a <- data.frame(X1=c("A", "B", "C", "A", "C", "D"),
                X2=c("B", "C", "D", "A", "B", "A"),
                X3=c("C", "D", "A", "B", "A", "B")
               )

And I have another set which is:-

b <- data.frame(Xn=c("A", "B", "C", "D"),
                Feature=c("some", "more", "what", "why"))

I want to add all the Features from set b to set a, such that X1, X2 and X3 have their corresponding feature column in set a. In other words, the columns in set a become:-

colnames(a) <- c("X1", "X2", "X3", "Features1", "Features2", "Features3")

How can I do this using a left_join in a for loop??

2 Answers

In base R, we can unlist a dataframe and match it with b$Xn to get corresponding Feature value. We can cbind this dataframe to original dataframe to get final answer.

temp <- a
temp[] <- b$Feature[match(unlist(temp), b$Xn)]
names(temp) <- paste0('Feature', seq_along(temp))
cbind(a, temp)

#  X1 X2 X3 Feature1 Feature2 Feature3
#1  A  B  C     some     more     what
#2  B  C  D     more     what      why
#3  C  D  A     what      why     some
#4  A  A  B     some     some     more
#5  C  B  A     what     more     some
#6  D  A  B      why     some     more

In tidyverse, we can get the data in long format, join the data and get it back to wide format.

library(dplyr)
library(tidyr)

a %>%
  mutate(row = row_number()) %>%
  pivot_longer(cols = -row) %>%
  left_join(b, by = c('value' = 'Xn'))  %>%
  select(-value) %>%
  pivot_wider(names_from = name, values_from = Feature) %>%
  select(-row) %>%
  rename_all(~paste0('Feature', seq_along(.))) %>%
  bind_cols(a, .)

This can be done by using mutate_all to recode all of the columns in a:

library(tidyverse)

a %>% 
  mutate_all(funs(feat=recode(., !!!set_names(as.character(b$Feature), b$Xn))))
  X1    X2    X3    X1_feat X2_feat X3_feat
1 A     B     C     some    more    what   
2 B     C     D     more    what    why    
3 C     D     A     what    why     some   
4 A     A     B     some    some    more   
5 C     B     A     what    more    some   
6 D     A     B     why     some    more

You can add a rename_at to get the desired names:

a %>% 
  mutate_all(funs(f=recode(., !!!set_names(as.character(b$Feature), b$Xn)))) %>% 
  rename_at(vars(matches("f")), ~gsub(".([0-9]).*", "Feature\\1", .))
  X1 X2 X3 Feature1 Feature2 Feature3
1  A  B  C     some     more     what
2  B  C  D     more     what      why
3  C  D  A     what      why     some
4  A  A  B     some     some     more
5  C  B  A     what     more     some
6  D  A  B      why     some     more
Related