如何在R中使用tidyeval创建包含所有因素水平的小型预测数据集?

如何解决如何在R中使用tidyeval创建包含所有因素水平的小型预测数据集?

我正在尝试使用modelr::data_grid()函数获得一个预测网格,该函数具有模型中一个因素的所有级别,而模型中另一个因素仅具有“典型”级别。问题在于,对预测网格中保持不变的因子的调用levels()应该返回原始数据中存在的所有级别。否则,某些预测功能可能会失败并返回臭名昭著的

Error in `contrasts<-`(`*tmp*`,value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels

这是我可以从modelr::data_grid()中学到的东西以及我想要的东西的证明。

library(tidyverse)

co2_mod <- slice(CO2,-1,-43)
fit <- lm(uptake ~ Type + Treatment,data = co2_mod)

grid_df <- modelr::data_grid(co2_mod,Type,.model = fit) %>%
  mutate(Treatment = factor(Treatment))
grid_df
#> # A tibble: 2 x 2
#>   Type        Treatment
#>   <fct>       <fct>    
#> 1 Quebec      chilled  
#> 2 Mississippi chilled
levels(grid_df$Treatment)
#> [1] "chilled"

我想拥有

levels(grid_df$Treatment)
[1] "nonchilled" "chilled"

数据集中只有1级的因子变量应“知道”原始数据集中的所有可能因子。例如,请参见下面的rstanarm小插曲的屏幕截图,其中显示了既需要将MaleFemale都设置为水平,也可以使gender等于Female

Screenshot to rstanarm article


我试图编写一些函数来实现我的目标。还有一个额外的步骤,就是将数据集重复1000次,因为我将这个网格用作newdata模型拟合的后验预测分布的rstanarm

辅助功能(有效):

get_all_levels <- function(v,dataset){
  v <- enquo(v)
  
  a <- select(dataset,!!v) %>% as_vector()
  l <- levels(a)
  
  return(l)
}

主函数,它调用辅助函数(这不起作用):

grid_all_levels <- function(model,variable,df){
  variable <- enquo(variable)
  grid <- expand_grid(
    rep = seq(1,1000,1),modelr::data_grid(df,!!variable,.model = model)
  ) %>%
    mutate(across(where(is.character),~factor(.,levels = get_all_levels(.,df))))
  
  return(grid)
}

这是一个小巧的代表,您可以在上面运行这些功能。

library(tidyverse)
  
get_all_levels <- function(v,dataset){
  v <- enquo(v)
  d <- as_tibble(dataset)
  a <- select(d,!!v) %>% as_vector()
  l <- levels(a)
  
  return(l)
}

grid_all_levels <- function(model,df))))
  
  return(grid)
}

co2_mod <- slice(CO2,-43)
fit <- lm(conc ~ Type + Treatment,data = co2_mod)
get_all_levels(Type,co2_mod)
#> [1] "Quebec"      "Mississippi"

grid_all_levels(fit,co2_mod)
#> Note: Using an external vector in selections is ambiguous.
#> ℹ Use `all_of(.)` instead of `.` to silence this message.
#> ℹ See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
#> This message is displayed once per session.
#> Error: Problem with `mutate()` input `..1`.
#> x Can't subset columns that don't exist.
#> x Columns `chilled`,`chilled`,etc. don't exist.
#> ℹ Input `..1` is `across(...)`.

我非常确定问题是我在.函数的get_all_levels调用中如何使用grid_all_levels

如何让grid_all_levels()工作?


更新

我按照以下答案修改了grid_all_levels()函数,使其看起来像这样:

grid_all_levels <- function(model,levels = get_all_levels(cur_column(),df))))
  
  return(grid)
}

返回

#> # A tibble: 2,000 x 3
#>      rep Type        Treatment
#>    <dbl> <fct>       <fct>    
#>  1     1 Quebec      chilled  
#>  2     1 Mississippi chilled  
#>  3     2 Quebec      chilled  
#>  4     2 Mississippi chilled  
#>  5     3 Quebec      chilled  
#>  6     3 Mississippi chilled  
#>  7     4 Quebec      chilled  
#>  8     4 Mississippi chilled  
#>  9     5 Quebec      chilled  
#> 10     5 Mississippi chilled  
#> # … with 1,990 more rows
levels(a$Treatment)
#> [1] "nonchilled" "chilled"

这正是我想要的!

解决方法

问题在于,对角线内的.是实际的列,而不是列的名称。遗憾的是,无法在across调用中获取名称,但是使用purrr::reduce可以解决:

library(tidyverse)
levelize <- function(.x,.y){
 mutate(.x,!!paste0(.y) := factor(!!sym(.y),levels =  get_all_levels(!!sym(.y),df) ) )
}

estimate_prevalence_differences_polr <- function(model,variable,df){
  variable <- enquo(variable)
  # putting the names of the factor variables inside a vector
  vars <- sapply(df,function(x) is.factor(x))
  vars <- names(vars)[vars]
  expand_grid(
    rep = 1:1000,modelr::data_grid(df,!!variable,.model = model)
  ) %>% 
### looping through the vars that are factor
## the .x argument is the one set by .init i.e the grid
## the .y argument is the element of the vars vector in the current iter
## the first iter we have .y="Type" and .x=.
## inside the levelize function
## basically mutate .x and change the variable named .y (Type) to become a factor
## with the levels returned from the original df
    reduce(intersect(vars,colnames(.)),levelize,.init=.)
}

现在调用该函数后,级别已正确设置,我们可以通过打印每个factor列的唯一值来进行检查:

estimate_prevalence_differences_polr(fit,Type,df) %>% select(where(is.factor)) %>% map(unique)
$Type
[1] Quebec      Mississippi
Levels: Quebec Mississippi

$Plant
[1] Qc2
Levels: Qn1 Qn2 Qn3 Qc1 Qc3 Qc2 Mn3 Mn2 Mn1 Mc2 Mc3 Mc1

$Treatment
[1] chilled    nonchilled
Levels: nonchilled chilled

编辑:

一种更简单的解决方案是使用cur_column,当我第一次编写答案时,我现在还没有使用此选项。因此基本上不是将.传递给get_all_levels,而是传递cur_column()

expand_grid(
    rep = seq(1,1000,1),.model = model)
  ) %>%
    mutate(across(where(is.character),~factor(.,levels = get_all_levels(cur_column(),df))))
,

我认为您正在使它变得比所需的更为复杂。如果我删除所有的tidyeval东西,我们会得到一个更简单的东西:

mutate(across(where(is.character),~ factor(.,levels = levels(.))))

您可以将~ lambda提取到可重用的命名函数中。

该实现立即使您想到了问题。由于levels()返回带有字符向量的NULL,因此这仅适用于因子。考虑到因素,这是无人操作的。我不确定您要达到什么目标。

此外,获取所有级别的实现还有一个问题:需要选择,它可以返回多个向量,例如与starts_with()。在这种情况下,您会得到一个令人困惑的错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res