以逗号分隔打印,删除引号并在 R 中添加特殊引号

Print separated by comma, remove quotes and add special quotes in R

我有一个 table,其中包含 TSV 格式的数据帧名称,如下所示:

df1 <- t(c('18-1829.tsv', '19-0193.tsv', '14-381.tsv', '19-940.tsv'))
df1

  V1          V2          V3         V4
1 18-1829.tsv 19-0193.tsv 14-381.tsv 19-940.tsv

我在 R 环境中拥有这些 .tsv 文件。我要做的是rbind他们,关于这个函数,里面应该是这样的:

df2 <- rbind(`18-1829.tsv`, `19-0193.tsv`, `14-381.tsv`, `19-940.tsv`)

请注意,我需要特殊引号 `` 才能使其正常运行。

所以我想做的是打印出一个文本,输出如下所示:

dfX <- `18-1829.tsv`, `19-0193.tsv`, `14-381.tsv`, `19-940.tsv`

所以我可以简单地 rbind(dfX) 并将它们全部绑定。

到目前为止我试过:

> paste(as.character(noquote(df1)), collapse="`, `")
[1] "18-1829.tsv`, `19-0193.tsv`, `14-381.tsv`, `19-940.tsv"

但这是相当错误的,因为它不会在开头或结尾输出 ``,而且开头有 [1],这可能会弄乱里面的东西 rbind。此外,开头和结尾的 "" 引号也可能会搞砸。

也许有更好的方法?

由于df1是一个矩阵,我们可以在其上使用mget。无需插入特殊引号。

do.call(rbind, mget(df1))

我们也可以使用 dplyr

中的 bind_rows
dplyr::bind_rows(mget(df1))

data.tablerbindlist

data.table::rbindlist(mget(df1))

使用可重现的例子

`18-1829.tsv` <- head(mtcars)
`19-0193.tsv` <- head(mtcars)
df1 <- t(c('18-1829.tsv', '19-0193.tsv'))
dplyr::bind_rows(mget(df1))

#    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#1  21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#2  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#3  22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#4  21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#5  18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#6  18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
#7  21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#8  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#9  22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#10 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#11 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#12 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

这里的主要问题是,在粘贴值之后,rbind 仍会将其视为字符串,不会将其编译为对象名称。

因此,您可以使用 mget,它采用正则表达式(正则表达式)和具有该名称的 returns 对象。之后有多种方式绑定数据。

绑定前

# Creating the dataframe which contains the names of your objects
df1 <- t(c('18-1829.tsv', '19-0193.tsv', '14-381.tsv', '19-940.tsv'))

# Simulating the objects that you have in your enviroment.
`18-1829.tsv` <- data.frame(a = 0)
`19-0193.tsv` <- data.frame(a = 0)
`14-381.tsv` <- data.frame(a = 0)
`19-940.tsv` <- data.frame(a = 0)

# Pasting the names of the objects and collapsing them using | meaning OR in regex
dfX <- paste0(noquote(df1), collapse = "|")
绑定方式一
df2 <- do.call(rbind, mget(ls(pattern = dfX)))
绑定方式二
library(dplyr)
df2 <- mget(ls(pattern = dfX)) %>% bind_rows()
绑定方式三
library(data.table)
df2 <- rbindlist(mget(ls(pattern = dfX)))