AleG
AleG

Reputation: 173

Use the names in multiple columns to create new columns

I have a dataset with 6 columns:

dataset

Alpha1 <- c(NA,'Place', NA, NA, 'Service')
Rating1 <- c(NA, 5, NA, NA, 5)
Alpha2 <- c(NA,'Rooms', NA, NA, 'Place')
Rating2 <- c(NA, 5, NA, NA, 3)
Alpha3 <- c(NA,'Service', NA, NA, 'Rooms')
Rating3 <- c(NA, 4, NA, NA, 0)

df <- data.frame(Alpha1, Rating1, Alpha2, Rating2, Alpha3, Rating3)

I´m trying to use the names in the fields Alpha1, Alpha2 and Alpha3 to create new columns, but respecting each observation. The result should be:

result

Upvotes: 1

Views: 40

Answers (1)

Taufi
Taufi

Reputation: 1577

Try the following.

  df %<>% .[complete.cases(.), ]
> df
   Alpha1 Rating1 Alpha2 Rating2  Alpha3 Rating3
2   Place       5  Rooms       5 Service       4
5 Service       5  Place       3   Rooms       0

Code

  cmbs <- list(df[, 1:2], df[, 3:4], df[,5:6]) %>%  
                          lapply(., function(x) setNames(x, c("Alpha", "Rating"))) %>% 
                               purrr::reduce(full_join, by = "Alpha") %>% 
                                                 data.table::transpose(.) %>% 
                                                    setNames(., .[1,]) %>% 
                                                       slice(-1)

Output

  Place Service Rooms
1     5       5  <NA>
2     3    <NA>     5
3  <NA>       4     0

Upvotes: 1

Related Questions