RSzT
RSzT

Reputation: 337

R dplyr: rowwise + mutate (+glue) - how to get/refer row content?

The simple example of input data:

dataset <- data.frame("part1" = c("a", "b", "c"),
                       "part2" = c("x", "y", "z"),
                       "caption" = c("{part1} {part2}",
                                     "{part2} {part1}",
                                     "{part2} {part1} {part2}"),
                       stringsAsFactors = F)

Expected results:

# A tibble: 3 x 3
  part1 part2 caption
  <chr> <chr> <chr>  
1 a     x     a x    
2 b     y     y b    
3 c     z     z c z  

The below code doesn't work, because . refers to the whole dataset, instead of data of the whole row content:

dataset %>%
  rowwise() %>%
  mutate("caption" =
           glue::glue_data(., caption)
         )

Question: how to pass row (all) content to glue?

The code that works (row "content" declared explicitly) is not what I've been looking for, because there are more columns used in caption "pattern" in my data set, thus I would like to avoid to declare it manually, just pass the whole row content.

dataset %>%
  rowwise() %>%
  mutate("caption" =
           glue::glue_data(
             list("part1" =  part1,
                  "part2" = part2)
             , caption)
  )

Upvotes: 1

Views: 1000

Answers (1)

Nicolas2
Nicolas2

Reputation: 2210

It works simply as:

dataset %>% rowwise %>% mutate(r=as.character(glue(caption)))
#Source: local data frame [3 x 4]
#Groups: <by row>

## A tibble: 3 x 4
#  part1 part2 caption                 r    
#  <chr> <chr> <chr>                   <chr>
#1 a     x     {part1} {part2}         a x  
#2 b     y     {part2} {part1}         y b  
#3 c     z     {part2} {part1} {part2} z c z

NOTE : I added the as.characteronly to avoid warnings that seem to be an issue with rowwise(Vectorizing 'glue' elements may not preserve their attributes)

Upvotes: 5

Related Questions