1.如何使用purrr按照行操作?
library(purrr)
df <- data.frame(
height = c(1.7, 1.8, 1.65),
weight = c(65, 72, 58)
)
# 计算每行的BMI
bmi <- pmap_dbl(df, function(height, weight, ...) {
weight / (height^2)
}
)2.如何传递列名封装为类似dplyr的函数?
library(dplyr)
library(rlang)
filter_by_col <- function(data, col, value) {
col <- enquo(col)
data %>% filter(!!col == value)
}
filter_by_col(mtcars, cyl, 6)
3.按物种分组保存为单独CSV文件?
library(dplyr)
iris %>%
group_by(Species) %>%
group_walk(~ write.csv(.x, file = paste0("iris_", .y$Species, ".csv")))4.如何获取从某一列到最后一列的列名?
library(tidyverse)
candidate_df <- tibble::tibble(
mapped_mass_1 = c(100.1, 200.2),
MF = c("H2O", "C6H12O6"),
raw = c("H2O", "C6H12O6"),
added_K = c("H2OK", "C6H12O6K"),
added_Na = c("H2ONa", "C6H12O6Na")
)
#方法1
mol_name <- colnames(candidate_df)[which(colnames(candidate_df) %in% "raw"):ncol(candidate_df)]
#方法2
mol_name <- candidate_df %>% select(raw:last_col()) %>% colnames()5.如何在purrr中使用自定义的函数?
library(dplyr)
library(purrr)
# 每个数据框都有一列叫 letter
datas2 <- list(
data.frame(id = 1:3, letter = c("A", "K", "C")),
data.frame(id = 4:6, letter = c("K", "B", "K"))
)
get_site_to_query <- function(df, site) {
df %>% filter(letter == site)
}
# 方法一:匿名函数
res <- map_dfr(datas2, function(x) { get_site_to_query(x, "K") })
# 方法二:参数传递(推荐)
res <- map_dfr(datas2, get_site_to_query, site = "K")