- 如何避免R读取数据格式时候出现错误? 安全读取
safe_read_any <- function(file, force_quote_empty = FALSE) {
message("Start reading ", basename(file))
ext <- tolower(tools::file_ext(file))
# 内部函数:用 readr 严格检查列名/结构
strict_readr_check <- function(func, ...) {
df <- func(..., name_repair = "check_unique", show_col_types = FALSE)
probs <- readr::problems(df)
if (nrow(probs) > 0) {
print(head(probs, 2))
stop(sprintf("文件 '%s' 中存在 %d 个数据问题(如列数不一致或重复列名)。", basename(file), nrow(probs)))
}
return(df)
}
# 设置 fread 的 quote 参数(按是否强制空 quote)
quote_opt <- if (force_quote_empty) "" else "\"'"
# 文件类型判断和读取逻辑
if (ext %in% c("tsv", "txt")) {
strict_readr_check(readr::read_tsv, file)
df <- data.table::fread(file, sep = "\t", quote = quote_opt, check.names = FALSE) |> as.data.frame()
} else if (ext == "csv") {
strict_readr_check(readr::read_csv, file)
df <- data.table::fread(file, quote = quote_opt, check.names = FALSE) |> as.data.frame()
} else if (ext %in% c("xlsx", "xls")) {
if (!requireNamespace("readxl", quietly = TRUE)) stop("Please install readxl to read Excel files.")
df <- tryCatch({
readxl::read_excel(file) |> as.data.frame()
}, error = function(e) {
message("readxl 读取失败,尝试当作文本读取")
data.table::fread(file, quote = quote_opt, check.names = FALSE) |> as.data.frame()
})
} else {
stop("不支持的文件类型: ", ext)
}
# 最终检查数据结构是否有效
if (nrow(df) == 0 || ncol(df) == 0) stop("读取到的表为空,请检查文件内容")
return(df)
}
- 如何使用switch进行多条件的选择?
x <- 2
result <- switch(x,
"1" = "一月",
"2" = "二月",
"3" = "三月",
"其他月份")
print(result) # 输出: "二月"
- reshape2的用法
library(reshape2)
df <- data.frame(
id = c(1, 2),
A = c(10, 20),
B = c(30, 40)
)
# 使用 id.vars 和 measure.vars
melted <- melt(
data = df,
id.vars = "id", # 保留 'id' 列
measure.vars = c("A", "B"), # 拉长 'A' 和 'B'
variable.name = "variable", # 新列名(原列名)
value.name = "value" # 新列名(数值)
)
library(tidyr)
df <- data.frame(
id = c(1, 2),
A = c(10, 20),
B = c(30, 40)
)
# 等效操作(两种写法)
melted <- df %>%
pivot_longer(
cols = c(A, B), # 或 cols = -id / cols = !id
names_to = "variable",
values_to = "value"
)
- 如何去除加载的基础包
if (!requireNamespace("pacman", quietly = TRUE)) install.packages("pacman")
pacman::p_unload(all = TRUE) # 卸载所有非基础包
gc()
- 如何将同一个KO所属的通路合并到一个单元格中?
library(tidyverse)
kegg_data <- data.frame(
KEGG_ID = c("ko00010", "ko00010", "ko00020", "ko00020", "ko00030", "ko00030", "ko00030"),
MAP = c("map00010", "map00500", "map00020", "map00600", "map00030", "map00230", "map00240")
)
# 查看原始数据
print(kegg_data)
kegg_merged <- kegg_data %>%
group_by(KEGG_ID) %>%
summarise(
MAP_merged = paste(MAP, collapse = ", "),
MAP_count = n() # 计数
)