1

我有一些名称为 a1、b1、c1 的对象,并希望使用带有名称的列表将它们全部合并到一个 df 中,而不是手动将它们写下来而不加引号。问题是我不知道如何删除引号以合并它们。这是我的代码:

a1=rnorm(10)
b1=rnorm(10)
c1=rnorm(10)

mylist=c("a1","b1","c1")
mylist2=gsub('"',"",mylist)
myarray=merge(mylist2)
4

1 回答 1

3

These aren't data.frame's so you can't merge them as you have in your example. Perhaps you meant to cbind these?

You can use do.call and use your actual data.frame's in a list and cbind them that way...

mylist = list(a1,b1,c1)
do.call("cbind",mylist)
#            [,1]       [,2]        [,3]
# [1,]  0.4221196 -1.2364700  1.71030549
# [2,]  0.2190202 -0.7730380 -0.27255412
# [3,] -0.1123769 -0.3365485  0.99418659
# [4,]  0.2940520 -1.2661584 -0.28545402
# [5,]  0.6301444 -1.3027926 -1.15401858
# [6,]  0.3505416  0.1636393  0.18114359
# [7,] -1.4592066  1.5832108  0.01407487
# [8,] -1.4251704 -1.1620232 -0.86712358
# [9,] -0.2840417 -2.3878617  0.57925139
#[10,] -0.9331564  1.1445266 -1.64355007

Of course here, you can just do cbind( a1, b1 , c1 ), so this notation is only handy if your vectors are in a list.

If you do want to merge them, the problem is that merge merges two data.frames, so you need a recursive function that adds a new data.frame to the result as you move through the list. Fortunately, such a function exists (it is actually quite simple to do), and is in Haldey's reshape package...

a1 <- data.frame( ID = 1:10 , A = rnorm(10) )
b1 <- data.frame( ID = 1:10 , B = rnorm(10) )
c1 <- data.frame( ID = 1:10 , C = rnorm(10) )
mylist <- list( a1 , b1 , c1 )


require(reshape)
merge_recurse( mylist )
#   ID          A           B           C
#1   1  0.4922820  1.44436959  0.49294607
#2   2  1.0198506  0.80738257 -1.51090757
#3   3  0.2403974  0.47383044 -0.74280235
#4   4  0.9697800 -1.06054666 -1.11042732
#5   5  1.4001970 -0.30221304  1.62866212
#6   6  0.4705122  0.02784419 -0.05886697
#7   7 -0.4259260  0.29810051  0.77933144
#8   8 -0.5102871  0.36181297  1.51223053
#9   9  1.1900207 -0.60902034 -0.32316668
#10 10 -0.1694786  0.20842787 -0.33366816
于 2013-06-18T08:25:24.027 回答