Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R data.frame() Function - Creating Data Frames

R data.frame() Function - Creating Data Frames

R Language Examples R Language Examples

The R data.frame() function is used to create a data frame, one of the most core data structures in R.

A data frame is similar to a table, where each column can hold a different type of data (numeric, character, logical, etc.), but all columns must have the same length.

The syntax of the data.frame() function is as follows:

data.frame(..., stringsAsFactors = default.stringsAsFactors())

Parameter Description:

Example

Create a data frame

df

<-

data.frame

(

  Number

=

1

:

5

,

  Name

=

c

(

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

,

"Qian Qi"

)

,

  Age

=

c

(

25

,

30

,

28

,

35

,

22

)

,

  Score

=

c

(

88

,

92

,

76

,

85

,

90

)

,

  stringsAsFactors

=

FALSE

)

print

(

"Data Frame Contents:"

)

print

(

df

)

View basic properties

print

(

"Structure:"

)

print

(

str

(

df

)

)

print

(

paste

(

"Number of Rows:"

,

nrow

(

df

)

,

"Number of Columns:"

,

ncol

(

df

)

)

)

print

(

"Column Names:"

)

print

(

colnames

(

df

)

)

The output of the code above is:

[1] "数据框内容:"

  编号 姓名 年龄 成绩

1    1 张三   25   88

2    2 李四   30   92

3    3 王五   28   76

4    4 赵六   35   85

5    5 钱七   22   90

[1] "结构:"

'data.frame':    5 obs. of  4 variables:

 $ 编号: int  1 2 3 4 5

 $ 姓名: chr  "张三" "李四" "王五" "赵六" ...

 $ 年龄: num  25 30 28 35 22

 $ 成绩: num  88 92 76 85 90

[1] "行数: 5 列数: 4"

[1] "列名:"

[1] "编号" "姓名" "年龄" "成绩"

R Language Examples R Language Examples