【问题标题】:Automatically create data frames based on factor levels of a column根据列的因子级别自动创建数据框
【发布时间】:2022-01-20 13:27:53
【问题描述】:

我有一些带有经理 ID、类型和位置的虚假案例数据。我想使用经理在给定位置的平均案例数自动创建数据框。

# create fake data
manager_id <- c(1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3)
type <- c("A", "A", "B", "B", "B", "A", "A", "A", "C", "A", "B", "B", "C", "C", "C")
location <- c("Beach", "Beach", "Beach", "Beach", "Beach", "City", "City", "City", "Farm", "Farm", "Farm", "Farm", "Farm", "Farm", "City")
manager_id <- data.frame(manager_id)
type <- data.frame(type)
location <- data.frame(location)
df <- cbind(manager_id, type, location)

创建假数据后,我创建了一个函数来找到这个平均值。该功能有效。

avgs_function <- function(dat){
dat1 <- dat %>% group_by(manager_id) %>% summarise(total = n())
total <- mean(dat1$total)
total <- round(total, 0)
total
}

然后我遍历每个位置,使用 avgs_function 创建数据帧,并将它们存储在一个列表中。然后我将数据框调用到我的全局环境中。这里出了点问题,我无法弄清楚。奇怪的是昨天还好好的。

df_list <- unique(df$location) %>%
           set_names() %>%
           map(~avgs_function(df))
names(df_list) <- paste0(names(df_list), "_avg")
list2env(df_list, envir = .GlobalEnv)

现在,代码给出了这些值:

Beach_avg = 5
City_avg = 5
Farm_avg = 5

我想要:

Beach_avg = 5
City_avg = 2
Farm_avg = 3

我相信问题出在 purrr 包上。任何帮助将不胜感激!

【问题讨论】:

  • @akrun 对不起,如果我仍然误解,但我确实得到了城市的平均 2。 city % filter(location == "City") city % group_by(manager_id) %>% summarise(total = n()) mean(city$total) 我希望有三个独立的向量,其中 Beach_avg = 5、City_avg = 2、Farm_avg = 3。
  • 我认为你需要df %&gt;% group_by(location) %&gt;% summarise(n = table(manager_id)) %&gt;% summarise(Mean = mean(n), .groups = 'drop')。我在想你需要它的另一种方式

标签: r dplyr


【解决方案1】:

我认为你根本不需要purrr(只需dplyr):这会得到你想要的输出

result <-(df 
  %>% count(manager_id, location) 
  %>% group_by(location) 
  %>% summarise(across(n, mean))
)

(尽管没有在位置名称中添加_avg:如果需要,您可以添加mutate(across(location, paste0, "_avg"))(或带有glue 的内容)

这也不会创建您想要的单独变量(尽管显然您可以添加更多内容,例如 with(result, setNames(list(n), location)) %&gt;% list2env(),但一般来说,使用一堆不同的命名变量填充您的全局工作区的工作流程是一个坏主意 - 集合如这通常可以通过将它们保存在列表/数据框/小标题中来更好地处理......

【讨论】:

  • 谢谢!此代码创建了我需要的单独数据框。结果 %>% split(.$location) %>% list2env(envir = .GlobalEnv)
  • 如果这解决了您的问题,我们鼓励您单击复选标记接受它...
猜你喜欢
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多