R中数据帧的[1],[1,],[,1],[[1]]有什么区别? [英] What's the difference between [1], [1,], [,1], [[1]] for a dataframe in R?

查看:33
本文介绍了R中数据帧的[1],[1,],[,1],[[1]]有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在 R 中,什么是访问列表元素的 [] 和 [[]] 符号的区别?

我对数据框类型的 [1]、[1,]、[,1]、[[1]] 的区别感到困惑.

I'm confused with the difference of [1], [1,], [,1], [[1]] for dataframe type.

据我所知,[1,] 将获取 matrix 的第一行,[,1] 将获取第一列.[[1]] 将获取 list 的第一个元素.

As I know, [1,] will fetch the first row of a matrix, [,1] will fetch the first column. [[1]] will fetch the first element of a list.

但是我查看了data.frame的文档,上面写着

But I checked the document of data.frame, which says

数据框是具有相同行数的变量列表唯一的行名

A data frame is a list of variables of the same number of rows with unique row names

然后我输入了一些代码来测试使用情况.

Then I typed in some code to test the usage.

>L3 <- LETTERS[1:3]
>(d <- data.frame(cbind(x=1, y=1:10), fac=sample(L3, 10, replace=TRUE)))
  x  y fac
1  1  1   C
2  1  2   B
3  1  3   C
4  1  4   C
5  1  5   A
6  1  6   B
7  1  7   C
8  1  8   A
9  1  9   A
10 1 10   A
> d[1]
   x
1  1
2  1
3  1
4  1
5  1
6  1
7  1
8  1
9  1
10 1
>d[1,]
  x y fac
1 1 1   C
>d[,1]
 [1] 1 1 1 1 1 1 1 1 1 1
>d[[1]]
 [1] 1 1 1 1 1 1 1 1 1 1

让我困惑的是:[1,] 和 [,1] 只用在 matrix 中.[[1]]只在list中使用,[1]在vector中使用,但为什么它们都在dataframe中可用?

What confused me is: [1,] and [,1] is only used in matrix. [[1]] is only used in list, and [1] is used in vector, but why all of them are available in dataframe?

谁能解释这些用法的区别?

Could anybody explain the difference of these usage?

推荐答案

在 R 中,运算符不只用于一种数据类型.运算符可以为您喜欢的任何数据类型重载(例如 S3/S4 类).

In R, operators are not used for one data type only. Operators can be overloaded for whatever data type you like (e.g. also S3/S4 classes).

事实上,data.frames 就是这种情况.

In fact, that's the case for data.frames.

  • 由于 data.frames 是列表,[i][[i]](和 $)显示列表类似的行为.

  • as data.frames are lists, the [i] and [[i]] (and $) show list-like behaviour.

行、列索引对于表格确实有直观的意义,而data.frames看起来像表格.可能这就是为什么要定义 data.frame [i, j] 方法的原因.

row, colum indices do have an intuitive meaning for tables, and data.frames look like tables. Probably that is the reason why methods for data.frame [i, j] were defined.

您甚至可以查看定义,它们是在 S3 系统中编码的(所以 methodname.class):

You can even look at the definitions, they are coded in the S3 system (so methodname.class):

> `[.data.frame`

> `[[.data.frame`

(反引号引用函数名,否则 R 会尝试使用运算符并最终出现语法错误)

(the backticks quote the function name, otherwise R would try to use the operator and end up with a syntax error)

这篇关于R中数据帧的[1],[1,],[,1],[[1]]有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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