我在R中有几个数据帧,需要以相同的方式进行处理。需要将输出打印到单独的文件中。这原则上可行,但是我无法自动将每个数据框的名称分配为相应的文件名。
我尝试了不同的方法,但是通过将数据帧组合到列表中,我走得最远了,
# Load libraries
library(tidyverse)
library(pheatmap)
# Make data frames and combine in list
df1 <- data.frame("Aa" = sample(LETTERS, 5), "Bb" = 1:5, "Cc" = 3:7)
df2 <- data.frame("Aa" = sample(LETTERS, 10), "Dd" = 8:17, "Ee" = 12:21)
dflist <- list(df1, df2)
# Assign names back to data frames in list
names(dflist) <- c("df1", "df2")
# Create heatmap with each data frame and save as separate pdf file:
lapply(dflist, function(x){
x_dflist_heatmap <- column_to_rownames(x, var = "Aa")
pdf(paste0("heatmap_", x, ".pdf"))
pheatmap(x_dflist_heatmap, scale = "row", main = paste0(x))
dev.off()
})
这会产生两个具有正确热图的pdf文件-以及非常有用的名称heatmap_c(2,5,1,4,4,3).pdf和heatmap_c(3,9,6,10,5,2,7,1 ,4,8).pdf。
我认为问题是我告诉R列出实际的数据帧,而不是其名称,但是我不知道如何解决。使用names(x)解释为使用每个数据帧的列名称。 额外的问题:这并不那么关键,但是如果有人可以让我知道如何将与“ x_dflist_heatmap”相对应的新生成的数据帧添加到我的R Data环境中,那真的很酷。
谢谢您的帮助!
答案 0 :(得分:0)
谢谢你们的投入!我认为这或多或少是您提出的,而且效果很好:
# Load libraries
library(tidyverse)
library(pheatmap)
# Make data frames and combine in list
df1 <- data.frame("Aa" = sample(LETTERS, 5), "Bb" = 1:5, "Cc" = 3:7)
df2 <- data.frame("Aa" = sample(LETTERS, 10), "Dd" = 8:17, "Ee" = 12:21)
dflist <- list(df1, df2)
# Assign names back to data frames in list
names(dflist) <- c("df1", "df2")
# Create list of the names of the data frames in dflist
dflist_names <- names(dflist)
# Modify the list of data frames for use with pheatmap and save as a new list
dflist_heatmap <- lapply(dflist, function(x){
x <- column_to_rownames(x, var = "Aa")
})
# Create separate pdf file for each data frame, using dflist_heatmap to generate the heatmap and dflist_names to name it
for(i in 1:length(dflist_names)){
pdf(paste0("heatmap_", dflist_names[[i]], ".pdf"))
pheatmap(dflist_heatmap[[i]], scale = "row", main = dflist_names[[i]])
dev.off()
}