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

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

我有一个表,其中包含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

这些.tsv文件我在R环境中提供。我要执行的操作是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内部的内容。同样,""引号在开始处和结尾处也可能使它弄乱。

也许有更好的方法可以做到这一点?

r printing paste rbind
2个回答
1
投票

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

do.call(rbind, mget(df1))

我们也可以使用bind_rows中的dplyr

dplyr::bind_rows(mget(df1))

data.table rbindlist

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

0
投票

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

相应地,您可以使用带正则表达式(正则表达式)并返回具有该名称的对象的mget。之后有多种方式绑定数据。

装订前

# 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 = "|")
装订方法1
df2 <- do.call(rbind, mget(ls(pattern = dfX)))
装订方法2
library(dplyr)
df2 <- mget(ls(pattern = dfX)) %>% bind_rows()
装订方法3
library(data.table)
df2 <- rbindlist(mget(ls(pattern = dfX)))
© www.soinside.com 2019 - 2024. All rights reserved.