gpt4 book ai didi

复制每一行并将一列更改为二进制值

转载 作者:行者123 更新时间:2023-12-04 09:50:58 25 4
gpt4 key购买 nike

df <- data.frame(n = c(3, 2, 2), 
survive = c(2, 1, 2),
a = c(1,1,0),
b = c(0,0,1))

如何扩展上面 data.frame 的最后两列,以便每行出现在列“n”中指定的次数。而第二列“survive”根据“survive”的值变为二进制值0/1

换句话说:
n  survive a  b
3 2 1 0
2 1 1 0
2 2 0 1

对此
survive a  b
1 1 0
1 1 0
0 1 0
1 1 0
0 1 0
1 0 1
1 0 1

最佳答案

几种替代解决方案:

1) 使用基础 R:

rn <- rep(1:nrow(df), df$n)
df2 <- df[rn,]
df2$survive <- as.integer(df2$survive >= ave(rn, rn, FUN = seq_along))

这使:
> df2[,-1]
survive a b
1: 1 1 0
2: 1 1 0
3: 0 1 0
4: 1 1 0
5: 0 1 0
6: 1 0 1
7: 1 0 1

2) 使用 data.table 包:
library(data.table)
df2 <- setDT(df)[, rid := .I
][, .(survive = c(rep(1, survive), rep(0, n - survive)), a, b)
, by = rid
][, rid := NULL][]

这使:
> df2
survive a b
1: 1 1 0
2: 1 1 0
3: 0 1 0
4: 1 1 0
5: 0 1 0
6: 1 0 1
7: 1 0 1

或者更短一点:
df2 <- setDT(df)[, .(survive = c(rep(1, survive), rep(0, n - survive)), a, b), by = 1:nrow(df)
][, nrow := NULL]

3) 使用 dplyr 包:
library(dplyr)
df %>%
mutate(rid = row_number()) %>%
.[rep(1:nrow(df), df$n),] %>%
group_by(rid) %>%
mutate(survive = c(rep(1, unique(survive)), rep(0, unique(n) - unique(survive))) ) %>%
ungroup() %>%
select(-n, -rid)

这使:
# A tibble: 7 × 3
survive a b
<dbl> <dbl> <dbl>
1 1 1 0
2 1 1 0
3 0 1 0
4 1 1 0
5 0 1 0
6 1 0 1
7 1 0 1

使用数据:
df <- data.frame(n = c(3, 2, 2), 
survive = c(2, 1, 2),
a = c(1,1,0),
b = c(0,0,1))

关于复制每一行并将一列更改为二进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com