r - 将布尔指标列转换为单因子列
问题描述
几年前在这里问过类似的问题。
我的设置有点不同。我的指标变量不是“真正的”虚拟变量,因为它们重叠。
我想做以下事情:
# fake data
library(tibble)
dat <- tribble(
~"a", ~"b", ~"c",
0, 0, 0,
1, 0, 0,
1, 1, 1
)
dat
#> # A tibble: 3 x 3
#> a b c
#> <dbl> <dbl> <dbl>
#> 1 0 0 0
#> 2 1 0 0
#> 3 1 1 1
# desired data
desired_col <- c("none", "a", "a,b,c")
cbind(dat, desired_col)
#> a b c desired_col
#> 1 0 0 0 none
#> 2 1 0 0 a
#> 3 1 1 1 a,b,c
由reprex 包(v0.2.0)于 2018 年 10 月 22 日创建。
请注意,列名将作为字符值粘贴到desired_col
. 如果不存在值,则值 == none
。如果存在多个值,则这些值用 分隔,
。
解决方案
这是使用 tidyverse 函数的一种方法
library(tibble)
library(dplyr)
library(tidyr)
dat %>%
rowid_to_column() %>% # keep data for each row together
gather("col", "val", -rowid) %>%
mutate(rowid=factor(rowid)) %>%
filter(val==1) %>%
group_by(rowid) %>%
summarize(desired=paste(col, collapse=",")) %>% #collapse values
complete(rowid, fill = list(desired="none")) # add "none" for empty groups
# rowid desired
# <fct> <chr>
# 1 1 none
# 2 2 a
# 3 3 a,b,c
基本思想涉及重塑数据,以便我们可以运行组函数,而不是在 data.frame 的行上运行函数,这并不容易。
推荐阅读
- python - 似乎无法将时间戳与 Python 中创建的日期范围相匹配
- android - 将 ClickListener 附加到列表项按钮单击自定义适配器
- log4net - 无法使用来自 GCE 实例的最新版本的 google.cloud.logging.log4net 将日志发送到 Stackdrvier
- node.js - 节点js中的对象数组变为空白
- excel - 再次,从网站接收数据的操作?
- spring - 如何在 Kotlin 和 Spring 中使用 setter 注入?
- security - 如何在 HTTP Post 期间使用 ZAP 自动进行主动扫描?
- postgresql - 从另一台计算机连接到我的 Postgresql
- sql-server-2014 - 最大行大小超过允许的最大值 8060 字节
- java - 无法在片段中创建 ArrayListAdapter