首页 > 解决方案 > 动态添加列和列名

问题描述

我有一个data.table这样的 R:

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

而且我想通过连续存在此 ID 来动态添加列。结果:

    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 

我尝试编写一个函数,或者使用 mutate 和 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))}

我收到一个错误:

错误:意外'=' in:“for(i in length(ids)) { df %>% mutate(paste("is_present",id[i]) ="

有人可以帮忙吗?

标签: rdynamicdplyrdata.table

解决方案


不确定我是否理解这个问题。但我认为您正在寻找具有动态列名称的 purr 映射函数。如果逻辑错误,您可以在函数内部进行调整。

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_"))

结果是:

  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

样本数据:

    df <- fread("
    id 
1:  1
2: 29
3: 26
4:  6
5:  1
6: 14") %>% 
  select(2) %>%  
  rownames_to_column("row")

推荐阅读