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

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

问题描述

假设我有一个 data.frame:

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

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

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

我尝试使用 as.data.frame(),它不会改变两列或更多列的结果.对于一列,它确实返回一个 data.frame,但不保留列名:

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

我不明白为什么它会这样.在我看来,提取一两列或十列应该不会有什么不同.它应该始终返回一个向量(或矩阵)或始终返回一个 data.frame(具有正确的名称).我错过了什么?谢谢!

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!

注意:这不是关于矩阵的问题的重复,因为矩阵和 data.frame 在 R 中是根本不同的数据类型,并且可以与 dplyr 不同地工作.有几个答案适用于 data.frame 但不适用于矩阵.

Note: This is not a duplicate of the question about matrices, as matrix and data.frame are fundamentally different data types in R, and can work differently with dplyr. There are several answers that work with data.frame but not matrix.

推荐答案

使用 drop=FALSE

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

来自文档(参见 ?"[") 你可以找到:

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

如果 drop=TRUE,结果将被强制转换为尽可能低的维度.

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

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

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