用 R 中向量中的值替换数据帧行名称
在本文中,我们将讨论如何在 R 编程语言中用向量中的值替换数据帧行名称。
使用中的数据框:
我们可以使用 rownames()函数替换行名称
句法:
rownames(dataframe) <- vector
在哪里,
- 数据框是输入数据框
- 向量是新的行值
示例: R 程序替换数据帧的行名
R
# create a dataframe with 6 rows and 2 columns
data = data.frame(sub1=c(100, 89, 90, 78, 98, 93),
sub2=c(89, 91, 97, 67, 100, 89))
# consider the vector
vec = c(10, 20, 30, 40, 50, 60)
# substitute the row names by values in a vector
rownames(data) = vec
# display dataframe
print(data)
R
# create a dataframe with 6 rows and 2 columns
data = data.frame(sub1=c(100, 89, 90, 78, 98, 93),
sub2=c(89, 91, 97, 67, 100, 89))
# consider the vector
vec = c("row1", "row2", "row3", "row4", "row5", "row6")
# substitute the row names by values in a vector
rownames(data) = vec
# display dataframe
print(data)
R
# create a dataframe with 6 rows and 2 columns
data = data.frame(sub1=c(100, 89, 90, 78, 98, 93),
sub2=c(89, 91, 97, 67, 100, 79))
# substitute the row names by sub1 column
rownames(data) = data$sub1
# display dataframe
print(data)
# substitute the row names by sub2 column
rownames(data) = data$sub2
# display dataframe
print(data)
输出:
示例: R 程序替换数据帧的行名
电阻
# create a dataframe with 6 rows and 2 columns
data = data.frame(sub1=c(100, 89, 90, 78, 98, 93),
sub2=c(89, 91, 97, 67, 100, 89))
# consider the vector
vec = c("row1", "row2", "row3", "row4", "row5", "row6")
# substitute the row names by values in a vector
rownames(data) = vec
# display dataframe
print(data)
输出:
我们还可以用数据帧中的值替换行名称
句法:
rownames(dataframe) <- dataframe$column_name
在哪里
- 数据框是输入数据框
- column_name 是数据框的列
示例: R 程序使用列替换数据框的行名
电阻
# create a dataframe with 6 rows and 2 columns
data = data.frame(sub1=c(100, 89, 90, 78, 98, 93),
sub2=c(89, 91, 97, 67, 100, 79))
# substitute the row names by sub1 column
rownames(data) = data$sub1
# display dataframe
print(data)
# substitute the row names by sub2 column
rownames(data) = data$sub2
# display dataframe
print(data)
输出: