Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
根据R中的条件向dataframe添加多个新列_R_Dataframe - Fatal编程技术网

根据R中的条件向dataframe添加多个新列

根据R中的条件向dataframe添加多个新列,r,dataframe,R,Dataframe,假设我有一个如下所示的数据集: library(tidyverse) df_raw <- data.frame(id = paste0('id', sample(c(1:13), replace = TRUE)), startTime = as.Date(rbeta(13, 0.7, 10) * 100, origin = "2016-01-01"), Channel = paste0('c', sample(c(1:3), 13, replace = TRUE, prob = c(0.

假设我有一个如下所示的数据集:

library(tidyverse)

df_raw <- data.frame(id = paste0('id', sample(c(1:13), replace = TRUE)), startTime = as.Date(rbeta(13, 0.7, 10) * 100, origin = "2016-01-01"), Channel = paste0('c', sample(c(1:3), 13, replace = TRUE, prob = c(0.2, 0.12, 0.3))) ) %>%
  group_by(id) %>%
  mutate(totals_transactions = sample(c(0, 1), n(), prob = c(0.9, 0.1), replace = TRUE)) %>%
  ungroup() %>%
  arrange(id, startTime)
现在,我想汇总相同的id,并将列添加到这个新的数据框中,以指示该id是否使用某个通道。我是这样做的:

seq_summaries <- df_raw %>%
  group_by(id) %>%
  summarize(
    c1_touches = max(ifelse(Channel == "c1",1,0)),
    c2_touches = max(ifelse(Channel == "c2",1,0)),
    c3_touches = max(ifelse(Channel == "c3",1,0)),
    conversions = sum(totals_transactions)
  ) %>% ungroup()

但是,我正在寻找一种不必为每个频道手动创建列的方法,因为频道的数量可能远远超过三个,这会导致大量工作。

这里有一个想法。请注意,您的数据帧中没有任何c2。要使用complete函数,您仍然需要提供c1到c3的完整列表

您应该使用dputdata而不是代码发布数据,特别是如果您没有使用base R。dmap_at来自哪里?@CPak我认为它来自Purrly,但OP已经删除了该行,因此现在不需要Purrly。
library(tidyverse)

df2 <- df_raw %>%
  group_by(id, Channel) %>%
  summarize(
    touches = 1L,
    conversions = as.integer(sum(totals_transactions))
  ) %>% 
  ungroup() %>%
  complete(Channel = paste0("c", 1:3)) %>%
  spread(Channel, touches, fill = 0L) %>%
  drop_na(id) %>%
  select(id, paste0("c", 1:3), conversions)
df2
# # A tibble: 8 x 5
#   id       c1    c2    c3 conversions
#   <fct> <int> <int> <int>       <int>
# 1 id10      1     0     0           0
# 2 id11      0     0     1           0
# 3 id12      0     0     1           1
# 4 id2       0     0     1           0
# 5 id3       0     0     1           0
# 6 id6       1     0     0           0
# 7 id8       1     0     0           1
# 8 id9       0     0     1           0