📜  在 R 中使用 cbind函数时设置列名

📅  最后修改于: 2022-05-13 01:55:49.348000             🧑  作者: Mango

在 R 中使用 cbind函数时设置列名

在本文中,我们将看到在 R 编程语言中使用 cbind()函数时如何设置列名。

让我们创建并组合两个向量进行演示:

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()
print(cbind(vector1, vector2))


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


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


输出:

[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()函数设置列名的 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()函数为三个向量设置列名的 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

输出: