2015-10-02 36 views
0

我知道如何通過列名稱調用data.frame,但它返回的是數字向量而不是data.frame。如何強制它返回一個data.frame呢?r按名稱調用列data.frame返回data.frame

data = data.frame(rand1 = rnorm(5, sd = 0.3),rand2 = rnorm(5, sd = 0.3)) 

data[,'rand2'] 

[1] 0.54355118 -0.34235808 0.30914102 -0.06509097 0.29061738 

class(data[,'rand2']) 

[1] "numeric" 
+0

以逗號出來。一個數據框是一個列表,所以你可以做'data [「rand2」]並保留data.frame類 –

+0

不錯......謝謝! – mmann1123

回答

0

從你的例子,你可以簡單地使用

data = data.frame(rand1 = rnorm(5, sd = 0.3),rand2 = rnorm(5, sd = 0.3)) 

data[,'rand2',drop=F] 

    rand2 
1 -0.07895436 
2 0.55478780 
3 -0.47263459 
4 0.17346880 
5 0.47885452 

class(data[,'rand2',drop=F]) 
[1] "data.frame" 

其他一些好點子data.frames可以發現here