gpt4 book ai didi

r - 使用列表填充数据框的列

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

我有以下数据框:

tibble(
people = rep(c("person1", "person2", "person3"), each = 4),
things = rep(c("thing1", "thing2", "thing3", "thing4"), times = 3),
vals = 0) %>%
group_by(people) %>%
mutate(order = seq_along(vals))
|people  |things | vals| order|
|:-------|:------|----:|-----:|
|person1 |thing1 | 0| 1|
|person1 |thing2 | 0| 2|
|person1 |thing3 | 0| 3|
|person1 |thing4 | 0| 4|
|person2 |thing1 | 0| 1|
|person2 |thing2 | 0| 2|
|person2 |thing3 | 0| 3|
|person2 |thing4 | 0| 4|
|person3 |thing1 | 0| 1|
|person3 |thing2 | 0| 2|
|person3 |thing3 | 0| 3|
|person3 |thing4 | 0| 4|

我也有“人”做过的“事”的 list 。

# What they did
list(
person1 = c(1, 3, 4),
person2 = c(2, 3),
person3 = NA
)

列表中的值指的是原始数据框的顺序列。所以 person1 做了事情 1、3 和 4,它们对应于顺序 order 列的数字 1、3 和 4。我想根据每个人所做的事情,使用列表来填写 vals 列。此示例的所需输出应如下所示:

|people  |things | vals| order|
|:-------|:------|----:|-----:|
|person1 |thing1 | 1| 1|
|person1 |thing2 | 0| 2|
|person1 |thing3 | 1| 3|
|person1 |thing4 | 1| 4|
|person2 |thing1 | 0| 1|
|person2 |thing2 | 1| 2|
|person2 |thing3 | 1| 3|
|person2 |thing4 | 0| 4|
|person3 |thing1 | 0| 1|
|person3 |thing2 | 0| 2|
|person3 |thing3 | 0| 3|
|person3 |thing4 | 0| 4|

我也尝试过使用 base R case_when,但我似乎无法理解如何做到这一点。

最佳答案

这是一个选项。我们使用 enframelist 更改为两列数据集,然后对原始数据集执行 right_join,按“people”分组,检查是否'order' 值是 %in% first unlisted 'value' 列,使用 + 强制转换为二进制>

library(dplyr)
library(tibble)
enframe(outlst, name = 'people') %>%
right_join(df1) %>%
group_by(people) %>%
mutate(vals = +(order %in% unlist(value[[1]]))) %>%
ungroup

-输出

# A tibble: 12 x 5
# people value things vals order
# <chr> <list> <chr> <int> <int>
# 1 person1 <dbl [3]> thing1 1 1
# 2 person1 <dbl [3]> thing2 0 2
# 3 person1 <dbl [3]> thing3 1 3
# 4 person1 <dbl [3]> thing4 1 4
# 5 person2 <dbl [2]> thing1 0 1
# 6 person2 <dbl [2]> thing2 1 2
# 7 person2 <dbl [2]> thing3 1 3
# 8 person2 <dbl [2]> thing4 0 4
# 9 person3 <lgl [1]> thing1 0 1
#10 person3 <lgl [1]> thing2 0 2
#11 person3 <lgl [1]> thing3 0 3
#12 person3 <lgl [1]> thing4 0 4

关于r - 使用列表填充数据框的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64613755/

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