R语言 使用cbind函数时设置列名
在这篇文章中,我们将看到如何在R编程语言中使用cbind()函数来设置列名。
让我们创建并合并两个向量进行演示。
# create two vectors with integer and string types
vector1 = c(1,2,3,4,5)
  
vector2 = c("sravan","bobby",
            "ojsawi","gnanesh",
            "rohith")
  
# display
print(vector1)
print(vector2)
  
# combine two vectors using cbind()
print(cbind(vector1, vector2))
输出
[1] 1 2 3 4 5
[1] "sravan"  "bobby"   "ojsawi"  "gnanesh" "rohith"  
    vector1 vector2  
[1,] "1"     "sravan"  
[2,] "2"     "bobby"  
[3,] "3"     "ojsawi"  
[4,] "4"     "gnanesh"
[5,] "5"     "rohith"
方法1:使用colnames()函数设置列名
R语言中的colnames()函数用于为矩阵的列设置名称。
语法:
colnames(x) <- value
参数:
x:  矩阵
value: 要设置的名称向量
例子: 使用colnames()函数来设置列名的R程序。
# create two vectors with integer and string types
vector1 = c(1,2,3,4,5)
  
vector2 = c("sravan","bobby","ojsawi",
            "gnanesh","rohith")
  
# display
print(vector1)
print(vector2)
  
# combine two vectors using cbind()
combined = cbind(vector1,vector2)
  
# Applying colnames
colnames(combined) = c("vector 1", "vector 2")    
  
# display
combined
输出
方法2:在cbind()函数中设置列名
在这里,我们必须在cbind()函数本身中给出列名。
语法: cbind(column_name = data1, column_name= data2,………,column_name=data n)
其中
- data 是要结合的输入数据
- column_name 是新的列名。
例子: 在cbind()函数中为三个向量设置列名的R程序
# create three vectors with integer and string types
vector1 = c(1,2,3,4,5)
  
vector2 = c("sravan","bobby","ojsawi",
            "gnanesh","rohith")
  
vector3 = c(12,34,21,34,51)
  
# display
print(vector1)
print(vector2)
print(vector3)
  
# combine three vectors with in  cbind() function
combined = cbind("ID"=vector1,
                 "NAME"=vector2,"AGE"=vector3)
  
# display
combined
输出
 极客教程
极客教程