在 R 中创建只有列名的空 DataFrame
在本文中,我们将使用 R 编程语言创建一个带有列名的空数据框。
创建数据框的基本语法是使用 data.frame()。
Syntax: data.frame(input_data,nrow,ncol)
Parameter:
- input_data may be values ot list or vector.
- nrow specifies the number of rows
- ncol specifies the number of columns.
脚步 -
- 创建一个空数据框
- 将列名定义为变量
- 将该变量分配给数据框。
- 显示如此创建的数据框
我们可以使用 colnames()将列名分配给数据框
句法:
colnames(dataframe_name)
下面给出了使用上述方法的实现。
示例 1:
R
# created vector with 5 characters
columns= c("id","names","address","phone","aadhar no")
# pass this vector length to ncol parameter
# and nrow with 0
myData = data.frame(matrix(nrow = 0, ncol = length(columns)))
# assign column names
colnames(myData) = columns
# display
print(myData)
R
# created vector with 5 characters
columns= c("id","names","address","phone","aadhar no")
# pass this vector length to ncol parameter
# and nrow with 1
myData = data.frame(matrix(nrow=1, ncol = length(columns)))
# assign column names
colnames(myData) = columns
# display
print(myData)
# pass this vector length to ncol parameter and
# nrow with 6
myData = data.frame(matrix(nrow=6, ncol = length(columns)))
# assign column names
colnames(myData) = columns
# display
print(myData)
输出:
[1] id names address phone aadhar no
<0 rows> (or 0-length row.names)
如果我们指定大于 0 的 nrow 参数,它将采用 NA 作为那么多行。
示例 2:
电阻
# created vector with 5 characters
columns= c("id","names","address","phone","aadhar no")
# pass this vector length to ncol parameter
# and nrow with 1
myData = data.frame(matrix(nrow=1, ncol = length(columns)))
# assign column names
colnames(myData) = columns
# display
print(myData)
# pass this vector length to ncol parameter and
# nrow with 6
myData = data.frame(matrix(nrow=6, ncol = length(columns)))
# assign column names
colnames(myData) = columns
# display
print(myData)
输出:
id names address phone aadhar no
1 NA NA NA NA NA
id names address phone aadhar no
1 NA NA NA NA NA
2 NA NA NA NA NA
3 NA NA NA NA NA
4 NA NA NA NA NA
5 NA NA NA NA NA
6 NA NA NA NA NA