r - 动态添加列和列名
问题描述
我有一个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]) ="
有人可以帮忙吗?
解决方案
不确定我是否理解这个问题。但我认为您正在寻找具有动态列名称的 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")
推荐阅读
- kubernetes - 如果您连接到多个集群,任何简单的方法来跟踪/维护 kubectl 配置 (./kube/config)
- list - 将对象从列表形成新对象
- javascript - 如何使用一些规则制作两个数组的循环
- image - 从 URL 中提取 svg
- javascript - 正则表达式:匹配字符串中不包含下划线的所有单词
- python - Python:只接受带有身份验证的套接字
- javascript - 通过更改商店/存档页面上的 +/- 数量从购物车中添加/删除
- highcharts - 在 Y 轴上的任意位置悬停时显示工具提示
- r - R编程:如果向量中的所有必需值都已从样本中复制,如何设置while循环条件?
- nuget - devops 工件提要在 Visual Studio 中不显示 nuget 包的图标