วิธีใช้ cbind ใน r (พร้อมตัวอย่าง)


ฟังก์ชัน cbind ใน R ย่อมาจาก column-bind สามารถใช้เพื่อรวมเวกเตอร์ เมทริกซ์ และเฟรมข้อมูลทีละคอลัมน์

ตัวอย่างต่อไปนี้แสดงวิธีใช้ฟังก์ชันนี้ในทางปฏิบัติ

ตัวอย่างที่ 1: การเชื่อมโยงเวกเตอร์ในเมทริกซ์

รหัสต่อไปนี้แสดงวิธีใช้ cbind เพื่อผูกเวกเตอร์แบบเรียงเป็นแนวสองตัวให้เป็นเมทริกซ์เดียว:

 #create two vectors
a <- c(1, 3, 3, 4, 5)
b <- c(7, 7, 8, 3, 2)

#cbind the two vectors into a matrix
new_matrix <- cbind(a, b)

#view matrix
new_matrix

     ab
[1,] 1 7
[2,] 3 7
[3,] 3 8
[4,] 4 3
[5,] 5 2

#view class of new_matrix
class(new_matrix)

[1] "matrix" "array" 

ตัวอย่างที่ 2: เชื่อมโยงเวกเตอร์กับกรอบข้อมูล

รหัสต่อไปนี้แสดงวิธีใช้ cbind เพื่อผูกเวกเตอร์กับกรอบข้อมูลที่มีอยู่:

 #create data frame
df <- data. frame (a=c(1, 3, 3, 4, 5),
                 b=c(7, 7, 8, 3, 2),
                 c=c(3, 3, 6, 6, 8))

#definevector
d <- c(11, 14, 16, 17, 22)

#cbind vector to data frame
df_new <- cbind(df, d)

#view data frame
df_new

  abcd
1 1 7 3 11
2 3 7 3 14
3 3 8 6 16
4 4 3 6 17
5 5 2 8 22

โปรดทราบว่า R จะส่งข้อผิดพลาดหากความยาวของเวกเตอร์ไม่เท่ากับความยาวของคอลัมน์ในกรอบข้อมูลที่มีอยู่

ตัวอย่างที่ 3: เชื่อมโยงเวกเตอร์หลายตัวเข้ากับกรอบข้อมูล

รหัสต่อไปนี้แสดงวิธีใช้ cbind เพื่อผูกเวกเตอร์หลายคอลัมน์กับกรอบข้อมูลที่มีอยู่:

 #create data frame
df <- data. frame (a=c(1, 3, 3, 4, 5),
                 b=c(7, 7, 8, 3, 2),
                 c=c(3, 3, 6, 6, 8))

#definevectors
d <- c(11, 14, 16, 17, 22)

e <- c(34, 35, 36, 36, 40) 

#cbind vectors to data frame
df_new <- cbind(df, d, e)

#view data frame
df_new

  a B C D E
1 1 7 3 11 34
2 3 7 3 14 35
3 3 8 6 16 36
4 4 3 6 17 36
5 5 2 8 22 40

ตัวอย่างที่ 4: รวมสองเฟรมข้อมูล

รหัสต่อไปนี้แสดงวิธีใช้ cbind เพื่อผูกสองเฟรมข้อมูลให้เป็นหนึ่งเดียว:

 #create two data frames
df1 <- data. frame (a=c(1, 3, 3, 4, 5),
                  b=c(7, 7, 8, 3, 2),
                  c=c(3, 3, 6, 6, 8))

df2 <- data. frame (d=c(11, 14, 16, 17, 22),
                  e=c(34, 35, 36, 36, 40))

#cbind two data frames into one data frame
df_new <- cbind(df1, df2)

#view data frame
df_new

  a B C D E
1 1 7 3 11 34
2 3 7 3 14 35
3 3 8 6 16 36
4 4 3 6 17 36
5 5 2 8 22 40

โบนัส: หากคุณต้องการผูกเวกเตอร์ เมทริกซ์ หรือเฟรมข้อมูลทีละแถว คุณสามารถใช้ฟังก์ชัน rbind แทนได้

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *