https://www.datamentor.io/r-programming/data-frame/

Check if a variable is a data frame or not

We can check if a variable is a data frame or not using the class() function.

> x
SN Age Name
1 1 21 John
2 2 15 Dora
> typeof(x) # data frame is a special case of list
[1] "list"
> class(x)
[1] "data.frame"

In this example, x can be considered as a list of 3 components with each component having a two element vector. Some useful functions to know more about a data frame are given below.


Functions of data frame

> names(x)
[1] "SN" "Age" "Name"
> ncol(x)
[1] 3
> nrow(x)
[1] 2
> length(x) # returns length of the list, same as ncol()
[1] 3

How to create a Data Frame in R?

We can create a data frame using the data.frame() function

For example, the above shown data frame can be created as follows.

> x <- data.frame("SN" = 1:2, "Age" = c(21,15), "Name" = c("John","Dora"))
> str(x) # structure of x
'data.frame': 2 obs. of 3 variables:
$ SN : int 1 2
$ Age : num 21 15
$ Name: Factor w/ 2 levels "Dora","John": 2 1

Notice above that the third column, Name is of type factor, instead of a character vector.

By default, data.frame() function converts character vector into factor.

To suppress this behavior, we can pass the argument stringsAsFactors=FALSE.

> x <- data.frame("SN" = 1:2, "Age" = c(21,15), "Name" = c("John", "Dora"), stringsAsFactors = FALSE)
> str(x) # now the third column is a character vector
'data.frame': 2 obs. of 3 variables:
$ SN : int 1 2
$ Age : num 21 15
$ Name: chr "John" "Dora"

Many data input functions of R like, read.table()read.csv()read.delim()read.fwf() also read data into a data frame.


How to access Components of a Data Frame?

Components of data frame can be accessed like a list or like a matrix.


Accessing like a list

We can use either [[[ or $ operator to access columns of data frame.

> x["Name"]
Name
1 John
2 Dora
> x$Name
[1] "John" "Dora"
> x[["Name"]]
[1] "John" "Dora"
> x[[3]]
[1] "John" "Dora"

Accessing with [[ or $ is similar. However, it differs for [ in that, indexing with [ will return us a data frame but the other two will reduce it into a vector.


Accessing like a matrix

Data frames can be accessed like a matrix by providing index for row and column.

To illustrate this, we use datasets already available in R. Datasets that are available can be listed with the command library(help = "datasets").

We will use the trees dataset which contains GirthHeight and Volume for Black Cherry Trees.

A data frame can be examined using functions like str() and head().

> str(trees)
'data.frame': 31 obs. of 3 variables:
$ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
$ Height: num 70 65 63 72 81 83 66 75 80 75 ...
$ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...
> head(trees,n=3)
Girth Height Volume
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2

We can see that trees is a data frame with 31 rows and 3 columns. We also display the first 3 rows of the data frame.

Now we proceed to access the data frame like a matrix.

> trees[2:3,]    # select 2nd and 3rd row
Girth Height Volume
2 8.6 65 10.3
3 8.8 63 10.2
> trees[trees$Height > 82,] # selects rows with Height greater than 82
Girth Height Volume
6 10.8 83 19.7
17 12.9 85 33.8
18 13.3 86 27.4
31 20.6 87 77.0
> trees[10:12,2]
[1] 75 79 76

We can see in the last case that the returned type is a vector since we extracted data from a single column.

This behavior can be avoided by passing the argument drop=FALSE as follows.

> trees[10:12,2, drop = FALSE]
Height
10 75
11 79
12 76

How to modify a Data Frame in R?

Data frames can be modified like we modified matrices through reassignment.

> x
SN Age Name
1 1 21 John
2 2 15 Dora
> x[1,"Age"] <- 20; x
SN Age Name
1 1 20 John
2 2 15 Dora

Adding Components

Rows can be added to a data frame using the rbind() function.

> rbind(x,list(1,16,"Paul"))
SN Age Name
1 1 20 John
2 2 15 Dora
3 1 16 Paul

Similarly, we can add columns using cbind().

> cbind(x,State=c("NY","FL"))
SN Age Name State
1 1 20 John NY
2 2 15 Dora FL

Since data frames are implemented as list, we can also add new columns through simple list-like assignments.

> x
SN Age Name
1 1 20 John
2 2 15 Dora
> x$State <- c("NY","FL"); x
SN Age Name State
1 1 20 John NY
2 2 15 Dora FL

Deleting Component

Data frame columns can be deleted by assigning NULL to it.

> x$State <- NULL
> x
SN Age Name
1 1 20 John
2 2 15 Dora

Similarly, rows can be deleted through reassignments.

> x <- x[-1,]
> x
SN Age Name
2 2 15 Dora

R Data Frame的更多相关文章

  1. R: data.frame 数据框的:查询位置、排序(sort、order)、筛选满足条件的子集。。

    ################################################### 问题:数据框 data.frame 查.排序等,   18.4.27 怎么对数据框 data.f ...

  2. R: data.frame 生成、操作数组。重命名、增、删、改

    ################################################### 问题:生成.操作数据框   18.4.27 怎么生成数据框 data.frame.,,及其相关操 ...

  3. R语言Data Frame数据框常用操作

    Data Frame一般被翻译为数据框,感觉就像是R中的表,由行和列组成,与Matrix不同的是,每个列可以是不同的数据类型,而Matrix是必须相同的. Data Frame每一列有列名,每一行也可 ...

  4. 如何将R中的data frame对象的数据导入到DB

    在使用ARIMA模型来预测我们的销量的时候,如果保存预测版本进DB,以供后续分析呢 1. 在定义变量阶段我们定义了dfResult      <- data.frame() 这是一个data f ...

  5. 将R非时间序列的data.frame转变为时序格式

    将R非时间序列的data.frame转变为时序格式,常常会用到,尤其是股票数据处理中, 举例:dailyData包括两列数据:Date Close10/11/2013 871.9910/10/2013 ...

  6. R语言 data.frame 大全

    A data frame is used for storing data tables. It is a list of vectors of equal length. For example, ...

  7. keep or remove data frame columns in R

    You should use either indexing or the subset function. For example : R> df <- data.frame(x=1:5 ...

  8. R语言合并data.frame

    Merging Data Adding Columns To merge two data frames (datasets) horizontally,  use the merge functio ...

  9. 转载:R语言Data Frame数据框常用操作

    Data Frame一般被翻译为数据框,感觉就像是R中的表,由行和列组成,与Matrix不同的是,每个列可以是不同的数据类型,而Matrix是必须相同的. Data Frame每一列有列名,每一行也可 ...

随机推荐

  1. 磁盘修复 mount: wrong fs type running e2fsck

    当服务器或PC机器的硬盘在使用一段时间后,会出现无法使用正常进行使用: 1. 当将文件系统挂载到指定的目录的时候,会出现mount 失败,如下图: [root@template ~]# mount / ...

  2. 使用 ASP.NET Core MVC 创建 Web API——响应数据的内容协商(七)

    使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...

  3. ElementUI table 点击编辑按钮进行编辑实现示例

    <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <meta nam ...

  4. 移动端H5页面开发,碰到一个字体变大的BUG

    移动端H5页面开发,碰到一个字体变大的BUG webkit内核下,对不定高宽的元素可能会放大其字体.那么,就可以设置一个max-width:或者使用-webkit-text-size-adjust: ...

  5. Centos7通过yum跟源码编译安装Nginx

    源码编译安装 http://nginx.org/en/download.html 到官网下载,然后用XFTP上传到root目录 把文件解压出来 tar -zxvf nginx-1.16.0.tar.g ...

  6. Python骚操作!一行命令把电脑变成服务器!

    不知道你有没有遇到这么一种情况,就是你有时候想要把电脑上的一些东西传输到你的手机或者 Pad ,你要么需要使用数据线连接到电脑,有时候还要装各种驱动才可以进行数据传输,要么需要借助第三方的工具,在局域 ...

  7. GO基础之接口

    一.概念1. 面向对象语言中,接口用于定义对象的行为.接口只指定对象应该做什么,实现这种行为的方法(实现细节)是由对象来决定.2. 在Go语言中,接口是一组方法签名. •接口只指定了类型应该具有的方法 ...

  8. CentOS 安装Asp.net Core & FTP服务

    网络设置 确认是否成功连网: ping baidu.com 如果无法上网请检查以下设置 ip link show vim /etc/sysconfig/network-scripts/ipcfg-(看 ...

  9. php5.6 上传图片error代码为6 或者 报错“PHP Warning: File upload error - unable to create a temporary file in Unknown on line 0”的解决办法

    问题:再利用webuploader上传图片的时候发现,报错,打印了$_FILES["file"]["error"] 发现是6,找不到临时文件夹: $_FILES ...

  10. java中文件复制的4种方式

    今天一个同事问我文件复制的问题,他一个100M的文件复制的指定目录下竟然成了1G多,吓我一跳,后来看了他的代码发现是自己通过字节流复制的,定义的字节数组很大,导致复制后目标文件非常大,其实就是空行等一 ...