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

如何将字符型DataFrame转换为指定数值以绘制热图

解决字符型DataFrame转自定义映射数值的问题

问题根源

你写的granule_coverter函数失效的核心原因是:用df$col时,R会把col当作字面列名,而不是你传入的参数变量。另外,多次嵌套ifelse不仅冗余,还容易因类型转换出现隐性错误。

解决方案

方法1:命名映射向量(最简洁高效)

先定义字符到数值的对应规则,再批量处理目标列:

# 自定义映射规则,可按需调整顺序和数值
map_rule <- c(
  'primary' = 1,
  'secondary' = 2,
  'tertiary' = 3,
  'ficolin-1' = 4,
  'secretory' = 5
)

# 复制原数据避免修改原始对象
df_num <- df_char
# 对指定列应用映射
df_num[, c('annoA', 'annoB', 'annoC')] <- lapply(df_num[, c('annoA', 'annoB', 'annoC')], function(x) {
  map_rule[x]
})

方法2:修正你的原函数

如果要保留函数形式,改用[[引用变量对应的列:

granule_converter <- function(df, cols) {
  for (col in cols) {
    df[[col]] <- ifelse(df[[col]] == 'primary', 1, df[[col]])
    df[[col]] <- ifelse(df[[col]] == 'secondary', 2, df[[col]])
    df[[col]] <- ifelse(df[[col]] == 'tertiary', 3, df[[col]])
    df[[col]] <- ifelse(df[[col]] == 'ficolin-1', 4, df[[col]])
    df[[col]] <- ifelse(df[[col]] == 'secretory', 5, df[[col]])
    # 强制转数值类型,非匹配值自动转为NA
    df[[col]] <- as.numeric(df[[col]])
  }
  return(df)
}

# 调用函数处理目标列
df_num <- granule_converter(df_char, cols = c('annoA', 'annoB', 'annoC'))

方法3:dplyr语法(适配tidyverse工作流)

如果习惯用tidyverse工具,用case_match实现精准映射:

library(dplyr)

df_num <- df_char %>%
  mutate(across(c(annoA, annoB, annoC), ~ case_match(
    .,
    'primary' ~ 1,
    'secondary' ~ 2,
    'tertiary' ~ 3,
    'ficolin-1' ~ 4,
    'secretory' ~ 5,
    .default = NA_real_
  )))

结果验证

运行任意方法后,得到的df_num与你期望的结果完全一致:

> df_num
     id annoA annoB annoC
1 Gene1     1     1     1
2 Gene2     2     1     2
3 Gene3     2     3     2
4 Gene4     1     3     1
5 Gene5    NA     3    NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:30:49