如何使用paste0()获取R中表格的列

问题描述 投票:0回答:1

我有一个特殊的情况,需要在

assign()
循环中使用
for
读取多个数据帧。然后我需要在绘图时使用
paste0()
函数访问特定列。作为测试,我不能简单地使用例如
head(paste0("a",2)$year)
来调用列数据。这给出了一个错误:
Error: object 'year' not found
。我也尝试过
head(paste0("a",2)[year]
但没成功。

assign(paste0("a",2), read.table("ft_sim_10000Ne_20hapS_1E_50G_05i_20Chr_15Mb_1_1_MSFS.final.summary",header=T,sep="\t")

这是我使用的简化代码。

library(gtools)
library(fs)
library(stringr)

pdf(paste0("combined.5rep.title.pdf"),width = 20, height = 25)
par(mfcol=c(5,5),mar=c(5,5,4,2)+0.2,cex.lab=1.6, cex.axis=1.3,lwd=2)
layout(matrix(c(1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),nrow=5,ncol=5,byrow=T),width=c(1,1),height=c(1,1))

for (event in c("00d","01d","05d","09d","05i")){
        ## folder_name: 
        ## ft_sim_100000Ne_80hapS_1E_50G_05i_20Chr_15Mb_1_MSFS
        ## ft_sim_100000Ne_20hapS_1E_50G_00d_20Chr_15Mb_1_MSFS
        ## file_name in each folder
        ## ft_sim_100000Ne_20hapS_1E_50G_00d_20Chr_15Mb_1_1_MSFS.final.summary
        ## ft_sim_100000Ne_20hapS_1E_50G_00d_20Chr_15Mb_1_2_MSFS.final.summary
        a1 <- read.table(mixedsort(sort(fs::dir_ls(path=paste0("./ft_sim_10000Ne_20hapS_1E_50G_",event,"_20Chr_15Mb_1_MSFS"), recurse = TRUE, type = "file", glob = "*20hapS*50G*MSFS.final.summary"))),header=T,sep="\t")
        plot(a1$year,a1$Ne_median,type="l", col="red")
        ## add plot title in each plot
        mtext(side=3,text=paste0("10000Ne_20hapS_1E_50G_",event,"_20Chr_15Mb"),cex=0.8,line=1.2)
        ## add 4 replicate lines using for-loop
        for (rep in c(2:5)){
            assign(paste0("a",rep), read.table(mixedsort(sort(fs::dir_ls(path=paste0("./ft_sim_10000Ne_20hapS_1E_50G_",event,"_20Chr_15Mb_1_",rep,"_MSFS"), recurse = TRUE, type = "file", glob = "*20hapS*50G*MSFS.final.summary"))),header=T,sep="\t"))
            print(head(paste0("a",rep,n=2L)))
            lines(paste0("a",rep)$year,paste0("a",rep)$Ne_median,type="l", col="orange")
        }
}
dev.off()

我的示例数据如下:

mutation_per_site n_estimation theta_per_site_median theta_per_site_2.5. theta_per_site_97.5.          year Ne_median  Ne_2.5. Ne_97.5. Ne_12.5. Ne_87.5.
1     4.940656e-324          200          1.040995e-08        3.802781e-09         2.878802e-08 1.372405e-315 0.7229131 0.264082 1.999168 0.438941 1.505282
2      3.903363e-12          200          1.040995e-08        3.802781e-09         2.878802e-08  1.084268e-03 0.7229131 0.264082 1.999168 0.438941 1.505282
3      5.151705e-12          200          1.040995e-08        3.802781e-09         2.878802e-08  1.431029e-03 0.7229131 0.264082 1.999168 0.438941 1.505282

我没有找到解决这个问题的方法。所以我的问题是如何解决这个问题。谢谢。

r dataframe for-loop paste
1个回答
0
投票

我不确定我完全理解你的问题,但我认为在访问你的数据时使用

get()
是缺失的。

head(get(paste0("a", 2))$year)

paste0("a", 2)
给出字符值
"a2"

get(paste0("a", "))
给出名为
a2
的对象的值。

© www.soinside.com 2019 - 2024. All rights reserved.