You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言gt包中为字符变量单元格设置填充色报错求助

问题解决方法

你的代码里有两个关键错误导致了这个报错:

  1. 多余括号导致变量赋值失败
    定义temp的行末尾多了一个无关的),这会让R解析错误,temp无法正确获取数据框,后续链式调用自然找不到有效的data参数。

  2. cells_body参数使用错误

    • columns = chr是无效写法,你需要指定具体列名(这里是oceans_names);
    • rows = chr = "Arctic"语法错误,应该用逻辑条件筛选行,比如oceans_names == "Arctic"。

修正后的完整代码:

# test data
oceans_names <- c("Arctic", "Atlantic", "Indian", "Pacific", "Southern")
avg_depth <- c(1.2, 3.65, 3.74, 3.97, 3.27)
highest_depth <- c(18, 30, 24, 36, 28)
oceans_highest_depth <- data.frame(oceans_names, highest_depth)

# set color for 'Arctic'
temp <- select(oceans_highest_depth, oceans_names, highest_depth)            
temp %>%
  gt() %>%
  tab_style(
    style = cell_fill(color = "cadetblue2"),
    locations = cells_body(
      columns = oceans_names,
      rows = oceans_names == "Arctic"
    ))

另外你重复定义了oceans_names,可以删掉其中一行,不影响结果但代码更整洁。

内容的提问来源于stack exchange,提问作者jacerl980

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:25:06