我有这样的R data.table
:
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和粘贴:
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个长度(ids)){ df%>%mutate(paste(“ is_present”,id [i])=“
有人可以帮忙吗?
答案 0 :(得分:0)
不确定我是否理解这个问题。但是我认为您正在从带有动态列名称的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")