diggi2395
diggi2395

Reputation: 335

Pivot_longer dependent on value in another column

My df looks like this:

Name   V1         V2         V3         choice
Apple  sports     sports     sports     v2
Banana hobbies    hobbies    hobbies    v3
Mango  interests  interests  interests  v1

I would like to manipulate the df to look like this using pivot_longer:

Name   choice choice_word
Apple  v2     hobbies
Banana v3     interests
Mango  v1     sports

Unfortunately, I could not find an appropriate answer online. Thanks!

Upvotes: 1

Views: 45

Answers (1)

akrun
akrun

Reputation: 887711

This can be done without pivot_longer - grouped by row (rowwise), convert the 'choice' to upper case (R is case sensitive), extract the column value with [[ from the data (cur_data()), ungroup and remove the columns not needed

library(dplyr)
df1 %>%
    rowwise %>%
    mutate(choice_word = cur_data()[[toupper(choice)]]) %>%
    ungroup %>%
    select(-(V1:V3))

If the 'v1', to 'v3', in 'choice' are the row numbers, then do

df1 %>% 
  transmute(Name, choice, 
     choice_word =  .[cbind(readr::parse_number(choice), 2:4)])

-output

    Name choice choice_word
1  Apple     v2     hobbies
2 Banana     v3   interests
3  Mango     v1      sports

data

df1 <- structure(list(Name = c("Apple", "Banana", "Mango"), V1 = c("sports", 
"hobbies", "interests"), V2 = c("sports", "hobbies", "interests"
), V3 = c("sports", "hobbies", "interests"), choice = c("v2", 
"v3", "v1")), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

Related Questions