0

I have an R data.table like this:

id
1:  1
2: 29
3: 26
4:  6
5:  1
6: 14`

And I would like to add columns dynamically by presence of this Id in a row. Result:

    id is_present_1 ... is_present_6....
1:  1            1                 0
2:  2            0                 0
3:  3            0                 0
4:  4            0                 1
5:  5            0                 0
6:  6            0                 1 

I tried to write a function, or using mutate and paste:

ids <- c(1, 2, 3, 4, 5, 6)
for (i in length(ids)) {
df %>% mutate(paste("is_present",id[i]) = ifelse(id == ids[i],1,0))}

I get an error:

Error: unexpected '=' in: "for (i in length(ids)) { df %>% mutate(paste("is_present",id[i]) ="

Can someone help with this?

kath
  • 7,624
  • 17
  • 32
Jenny
  • 15
  • 4
  • You need to use tidy evaluation to create dynamic names within `dplyr` verbs. See some examples here: https://stackoverflow.com/q/49700912/786542 & https://maraaverick.rbind.io/2017/08/tidyeval-resource-roundup/ – Tung Nov 12 '18 at 07:47

1 Answers1

0

Not sure if I understand the question. But i think you are looking for a map function from purr with dynamic columns names. If the logic is wrong you can just adjust inside the function.

library(tidyverse)
library(data.table)

map_dfc(df$row, function(x){
nm <- paste("is_present_", x, sep = "")
  df %>% 
    mutate(!!nm := ifelse(id == x, 1, 0))}) %>% 
  select(contains("is_present_"))

results in:

  is_present_1 is_present_2 is_present_3 is_present_4 is_present_5 is_present_6
1            1            0            0            0            0            0
2            0            0            0            0            0            0
3            0            0            0            0            0            0
4            0            0            0            0            0            1
5            1            0            0            0            0            0
6            0            0            0            0            0            0

Sample data:

    df <- fread("
    id 
1:  1
2: 29
3: 26
4:  6
5:  1
6: 14") %>% 
  select(2) %>%  
  rownames_to_column("row")
davsjob
  • 1,882
  • 15
  • 10