Christian
Christian

Reputation: 477

using mutate with purrr's map


how could I add a column in a tibble which is in a list?
The data looks like the following and I just want to add a column at the end which checks if column 2 is the same as 3

[[1]]
# A tibble: 620 x 4
   DataName              `Technischer Platz...4` `Technischer Platz...5` `Technischer Platz...307`
   <chr>                 <chr>                   <chr>                   <lgl>                    
 1 WrW_SAPP17_VIAUFKAFVC 1202362-001             1202362-001             NA                       
 2 WrW_SAPP17_VIAUFKAFVC 1202362-002 037         1202362-002 037         NA                       
 3 WrW_SAPP17_VIAUFKAFVC 1202362-011             1202362-011             NA                       
 4 WrW_SAPP17_VIAUFKAFVC 1202362                 1202362                 NA                       
 5 WrW_SAPP17_VIAUFKAFVC 1202362-004 052         1202362-004 052         NA                       
 6 WrW_SAPP17_VIAUFKAFVC 1202362-018 005         1202362-018 005         NA                       
 7 WrW_SAPP17_VIAUFKAFVC 1202362-017             1202362-017             NA                       
 8 WrW_SAPP17_VIAUFKAFVC 1202362-012             1202362-012             NA                       
 9 WrW_SAPP17_VIAUFKAFVC 1202362-002 002         1202362-002 002         NA                       
10 WrW_SAPP17_VIAUFKAFVC 1202362-002 039         1202362-002 039         NA

Upvotes: 0

Views: 1034

Answers (2)

William
William

Reputation: 164

Let's use a simpler example

library(tidyverse)

honda <- tibble(brand = "HONDA",
                disp  = c(3, 8, 20),
                hp    = c(3, 90, 115)) 

volvo <- tibble(brand = "VOLVO",
                disp  = c(3, 8, 20),
                hp    = c(3, 34, 115)) 

list_df <- list(honda, volvo)


list_df %>% map(~ mutate(., check = disp == hp))
#> [[1]]
#> # A tibble: 3 x 4
#>   brand  disp    hp check
#>   <chr> <dbl> <dbl> <lgl>
#> 1 HONDA     3     3 TRUE 
#> 2 HONDA     8    90 FALSE
#> 3 HONDA    20   115 FALSE
#> 
#> [[2]]
#> # A tibble: 3 x 4
#>   brand  disp    hp check
#>   <chr> <dbl> <dbl> <lgl>
#> 1 VOLVO     3     3 TRUE 
#> 2 VOLVO     8    34 FALSE
#> 3 VOLVO    20   115 FALSE

Created on 2021-02-18 by the reprex package (v1.0.0)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389275

We can use :

library(dplyr)
library(purrr)

list_df <- map(list_df, ~.x %>% 
            mutate(is_2_same_as_3 = `Technischer Platz...4` == `Technischer Platz...5`))

If you want to do it based on position of columns use :

list_df <- map(list_df, ~.x %>% 
                          mutate(is_2_same_as_3 = .[[2]] == .[[3]]))

Same in base R would be using lapply :

list_df <- lapply(list_df, function(x) transform(x, is_2_same_as_3 = `Technischer Platz...4` == `Technischer Platz...5`))
list_df <- lapply(list_df, function(x) transform(x, is_2_same_as_3 = x[[2]] == x[[3]]))

Upvotes: 1

Related Questions