如何从data.frame中提取单个列作为数据框架? [英] How do I extract a single column from a data.frame as a data.frame?

查看:253
本文介绍了如何从data.frame中提取单个列作为数据框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个data.frame:

  df<  -  data.frame(A = c(10,20 ,30),B = c(11,22,33),C = c(111,222,333))
ABC
1 10 11 111
2 20 22 222
3 30 33 333

如果我选择两个(或更多)列,我得到一个data.frame:

  x<  -  df [,1:2] 
AB
1 10 11
2 20 22
3 30 33

这是我想要的。但是,如果我只选择一列,我会得到一个数字向量:

  x < -  df [,1] 
[1] 1 2 3

我试图使用as.data.frame()不会更改两列或更多列的结果。它会在一列的情况下返回一个data.frame,但不保留列名称:

  x < as.data.frame(df [,1])$ ​​b $ b df [,1] 
1 1
2 2
3 3

我不明白为什么它的行为是这样的。在我看来,如果我提取一个或两个或十个列,它不应该有所作为。它应该总是返回一个向量(或矩阵)或者总是返回一个data.frame(具有正确的名称)。我失踪了什么?谢谢!

解决方案

使用 drop = FALSE

 > x<  -  df [,1,drop = FALSE] 
> x
A
1 10
2 20
3 30

从文档中(请参阅 ? [ )您可以找到:


如果drop = TRUE,结果被强制转换为最低的维度。



Say I have a data.frame:

df <- data.frame(A=c(10,20,30),B=c(11,22,33), C=c(111,222,333))
  A  B  C
1 10 11 111
2 20 22 222
3 30 33 333

If I select two (or more) columns I get a data.frame:

x <- df[,1:2]
   A  B
 1 10 11
 2 20 22
 3 30 33

This is what I want. However, if I select only one column I get a numeric vector:

x <- df[,1]
[1] 1 2 3

I have tried to use as.data.frame(), which does not change the results for two or more columns. it does return a data.frame in the case of one column, but does not retain the column name:

x <- as.data.frame(df[,1])
     df[, 1]
1       1
2       2
3       3

I don't understand why it behaves like this. In my mind it should not make a difference if I extract one or two or ten columns. IT should either always return a vector (or matrix) or always return a data.frame (with the correct names). what am I missing? thanks!

解决方案

Use drop=FALSE

> x <- df[,1, drop=FALSE]
> x
   A
1 10
2 20
3 30

From the documentation (see ?"[") you can find:

If drop=TRUE the result is coerced to the lowest possible dimension.

这篇关于如何从data.frame中提取单个列作为数据框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆