嗨,请帮帮我
我有一个带标头的数据帧
csvfile
experiment control par1 par2 par3
1 a 1 11 21
1 b 5 12 21
2 a 2 11 50
2 b 3 13 31
3 a 4 11 35
3 b 2 11 35
所以我想遍历列名(实验和对照除外(
for (i in column_name)
{
if (i !="experiment" & i !="control )
{filename = paste(i, 'plot.jpg', sep = '_')
save_path = paste('/filepath', filename, sep='/')
print(csvfiles$i)
jpeg(save_path, width = 1083, height = 643)
p1 <- ggplot(csvfiles, aes(x=control, y= i, color = control)) + geom_violin() + geom_boxplot(width = 0.1)
print(p1)
dev.off()
}
}
现在我看到问题 R 在考虑 y = i = 字符串而不是查看数据帧[i] 自打印(csvfiles$i( -> NULL
我该如何解决这个问题?
谢谢
我们可以创建一个函数,使用一些非标准求值从数据中访问列名
library(ggplot2)
create_plots <- function(data, col) {
filename = paste(col, 'plot.jpg', sep = '_')
save_path = paste('/filepath', filename, sep='/')
jpeg(save_path, width = 1083, height = 643)
p1 <- ggplot(data, aes(x=control, y= !!sym(col), color = control)) +
geom_violin() + geom_boxplot(width = 0.1)
print(p1)
dev.off()
}
并使用lapply
将其应用于不同的列名
cols <- names(df)[!names(df) %in% c('experiment', 'control')]
lapply(cols, create_plots, data = df)