这里我们解释如何编写 R 程序来更改给定数据框的列名。这里我们使用内置函数 data.frame()。数据框用于存储数据表,其中包含等长向量列表。数据框由函数 data.frame() 创建,它具有紧密耦合的变量集合。此函数的语法是,
data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE, fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors())
其中点(...)表示参数的形式为 value 或 tag = value,而 row.name 是一个 NULL 或单个整数或字符串。
以下是 R 程序中用于更改给定数据框列名的步骤。在此 R 程序中,我们直接将数据框提供给内置函数。这里我们使用变量 E、N、S、A、Q 来存储不同类型的向量。调用函数 data.frame() 创建 数据框。最后,通过调用 colnames(E)[which(names(E) == "N")] = "S_N"来更改数据框的列名。
步骤1:使用向量值为变量E、N、S、A、Q赋值
步骤2:首先打印原始向量值
步骤 3:通过调用 colnames(E)[which(names(E) == "N")] = "S_N"将列 N 更改为 S_N
步骤4:打印最终的数据框
E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original dataframe:")
print(E)
print("Change column-name 'N' to 'S_N' of the data frame:")
colnames(E)[which(names(E) == "N")] = "S_N"
print(E)
[1] "Original dataframe:"
N S A Q
1 Jhon 10.0 2 yes
2 Hialy 9.5 1 no
3 Albert 12.2 2 yes
4 James 11.0 4 no
5 Delma 8.0 1 no
[1] "Change column-name 'N' to 'S_N' of the data frame:"
S_N S A Q
1 Jhon 10.0 2 yes
2 Hialy 9.5 1 no
3 Albert 12.2 2 yes
4 James 11.0 4 no
5 Delma 8.0 1 no