R data.frame() Function - Creating Data Frames
The R data.frame() function is used to create data frames, which are one of the core data structures in R.
A data frame is similar to a table. Each column can contain a different type of data (numeric, character, logical, etc.), but each column must have the same length.
The syntax of the data.frame() function is as follows:
data.frame(..., stringsAsFactors = default.stringsAsFactors())
Parameter description:
...Column data, can be vectors, lists, or matrices.
stringsAsFactorsWhether to automatically convert strings to factors (defaults to FALSE since R 4.0).
Example
# Create a data frame
df <- data.frame(
ID= 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 attributes
print("Structure:")
print(str(df))
print(paste("Number of rows:", nrow(df), "Number of columns:", ncol(df)))
print("Column names:")
print(colnames(df))
df <- data.frame(
ID= 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 attributes
print("Structure:")
print(str(df))
print(paste("Number of rows:", nrow(df), "Number of columns:", ncol(df)))
print("Column names:")
print(colnames(df))
Running the above code produces the following output:
[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] "编号" "姓名" "年龄" "成绩"Other Extensions
R Language Examples