在bind_rows中将字符串用作变量名 [英] apply strings as variable names in bind_rows
本文介绍了在bind_rows中将字符串用作变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的数据框的名称可以轻松地通过粘贴来重新创建,但是结果不能输入到bind_rows中.
The names of the dataframes below can easily be recreated with paste, but the result cannot be fed into bind_rows.
以下是一致命名的数据帧(x1,x2,x3):
Here are consistently named dataframes (x1, x2, x3):
library(dplyr)
x1 <- tibble(col1 = state.abb[1:3])
x2 <- tibble(col1 = state.abb[4:6])
x3 <- tibble(col1 = state.abb[7:9])
bind_rows可以....但是键入每个名称很繁琐
bind_rows works....but typing each name is tedious
bind_rows(x1,x2,x3)
#> # A tibble: 9 x 1
#> col1
#> <chr>
#> 1 AL
#> 2 AK
#> 3 AZ
#> 4 AR
#> 5 CA
#> 6 CO
#> 7 CT
#> 8 DE
#> 9 FL
我想用粘贴或其他相对简单的方法来创建名称
I would like to create the names with paste, or some comparably simple way
created.names <- paste0("x", 1:3)
[1] "x1" "x2" "x3"
bind_rows(created.names)
#> Error in bind_rows_(x, .id): Argument 1 must have names
由 reprex程序包(v0.2.0)创建于2018-07-03.
Created on 2018-07-03 by the reprex package (v0.2.0).
推荐答案
在 bind_rows
之前的名称上使用 mget
,这将返回具有所提供名称的数据帧列表:
Use mget
on the names before bind_rows
, which returns a list of data frames with the names provided:
bind_rows(mget(created.names))
# A tibble: 9 x 1
# col1
# <chr>
#1 AL
#2 AK
#3 AZ
#4 AR
#5 CA
#6 CO
#7 CT
#8 DE
#9 FL
这篇关于在bind_rows中将字符串用作变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文