pivot_wider 基于 0 或 1 的条件 [英] pivot_wider based on condition of a 0 or 1
本文介绍了pivot_wider 基于 0 或 1 的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对我的数据使用 pivot_wider
.数据如下:
I am trying to use pivot_wider
on my data. The data looks like:
dates yes_no
1 2017-01-01 0
2 2017-01-02 1
3 2017-01-03 0
4 2017-01-04 1
5 2017-01-05 1
我试图获得预期输出的地方:
Where I am trying to get the expected output to be:
dates yes_no 2017-01-02_1 2017-01-04_1 2017-01-05_1
1 2017-01-01 0 0 0 0
2 2017-01-02 1 1 0 0
3 2017-01-03 0 0 0 0
4 2017-01-04 1 0 1 0
5 2017-01-05 1 0 0 1
当 yes_no
列有 1 英寸时,数据已经spread
.
Where the data has been spread
when the yes_no
column has a 1 in.
这对我不起作用:
d %>%
mutate(value_for_one_hot = 1) %>%
pivot_wider(names_from = dates, values_from = value_for_one_hot,
names_prefix = "date_", values_fill = list(value_for_one_hot = 0))
数据:
data.frame(
dates = c("2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05"),
yes_no = c(0, 1, 0, 1, 1)
)
推荐答案
这里有一个 data.table 方法实际上并没有重塑数据.
Here's a data.table approach that does not actually reshape the data.
library(data.table)
setDT(d)
ind <- d[['yes_no']] != 0
cols <- as.character(d[['dates']])[ind]
d[, (cols) := 0L]
d[ind, (cols) := as.data.frame(diag(.N))]
## also valid
# set(d, which(ind), cols, as.data.frame(diag(length(cols))))
d
这篇关于pivot_wider 基于 0 或 1 的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文