使用列表填充数据框的列

时间:2020-10-30 18:15:03

标签: r tidyverse data-wrangling

我有以下数据框:

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|

我还列出了“人们”所做的“事情”。

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

列表中的值引用原始数据帧的顺序列。因此,person1进行了与第order列的数字1、3和4对应的事情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|

我也尝试过使用基数R case_when,但是我似乎无法理解该怎么做。

2 个答案:

答案 0 :(得分:3)

这是一个选项。我们使用listenframe更改为两列数据集,然后对按“人”分组的原始数据集进行right_join,检查“订单”值是否为{{1 }} %in% first编辑的“值”列,使用unlist

强制转换为二进制
+

-输出

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

答案 1 :(得分:2)

基本R选项

app.use(
  cors({
    exposedHeaders: ["custom-header"]
  })
);

给出

transform(
  merge(
    subset(df, select = -vals),
    cbind(subset(stack(lst), !is.na(values)), vals = 1),
    by.x = c("people", "order"),
    by.y = c("ind", "values"),
    all = TRUE
  ),
  vals = replace(vals, is.na(vals), 0)
)[names(df)]

数据

    people things vals order
1  person1 thing1    1     1
2  person1 thing2    0     2
3  person1 thing3    1     3
4  person1 thing4    1     4
5  person2 thing1    0     1
6  person2 thing2    1     2
7  person2 thing3    1     3
8  person2 thing4    0     4
9  person3 thing1    0     1
10 person3 thing2    0     2
11 person3 thing3    0     3
12 person3 thing4    0     4
相关问题