2017-03-14 151 views
1

我想在下面的例子中将一个列表绑定到数据框。我想要每行的行号,但是我得到每一行,以及整个列表。这只是我想要做的简化,但原理是一样的。cbind,垂直而不是水平

mtcars是32 obs的数据帧。 11个变量

的我在寻找使它32个OBS 12个变量,其中新列在列表中,而不是我得到32个OBS 43个变量

任何帮助将是非常赞赏的

the_list <- list() 
for (i in 1:nrow(mtcars)) 
{ 
    the_list[i] <- i 
} 

test <- cbind(mtcars, the_list) 
+3

不要使用列表,而是使用向量。你可以在后面创建一个向量,比如''unlist'“:'test < - cbind(mtcars,unlist(the_list))'或者只是得到一个行号'test < - cbind(mtcars,seq_along(mtcars [,1 ]))'。 – lmo

+2

'mtcars $ row_number = 1:nrow(mtcars)'有效吗? – Fernando

回答

0

lmo的回复是正确的。

测试< - cbind(mtcars,不公开(the_list))

0

如果您rownames只是数字1 ... nrow(),然后简单地做:

mtcars %>% rownames_to_column(var='the_list') 
0

不知道为什么你会希望它是一个列表,而不是像其他列向量的列表,但下面的工作

mtcars$listCol <- as.vector(x = 1:nrow(mtcars), mode = "list")