📜  如何将行附加到 R DataFrame ?

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

如何将行附加到 R DataFrame ?

在本文中,让我们讨论如何在 R 编程语言中将行附加到 DataFrame。有多种方法可以将行附加到 R 数据框:

方法一:使用rbind()

可以使用值向量定义行,并使用 rbind() 方法附加到数据帧,这实质上意味着行绑定。此方法可用于组合两个向量、一个数据帧和一个向量,甚至两个或多个数据帧。为了保留更改,必须将输出分配给原始或修改后的数据框。在这种情况下,行数增加一。 rbind() 方法具有以下语法:

例子:

R
# declaring a data frame in R
data_frame = data.frame(C1 = c(1:4),
                        C2 = c(5:8),
                        C3 = c(9:12),
                        C4 = c(13:16))
  
print("Original data frame")
print(data_frame)
  
# defining new row data frame
new_row = c("New","Row","Added","Dataframe")
  
# bind a new row to the original data frame
data_frame <- rbind(data_frame,new_row)
print ("Modified Data Frame")
print(data_frame)


R
# declaring a data frame in R
data_frame = data.frame(C1 = c(1:4),
                        C2 = c( 5:8), 
                        C3 = c(9:12),
                        C4 = c(13:16))
  
print("Original data frame")
print(data_frame)
  
# calculating number of rows in data frame
num_rows = nrow(data_frame)
  
# defining new row data frame
new_row = c("New","Row","Added","Dataframe")
  
# assigning the new row at a new
# index after the original number of rows 
data_frame[num_rows + 1,] = new_row
print ("Modified Data Frame")
print(data_frame)


输出:

[1] "Original data frame"
 C1 C2 C3 C4
1  1  5  9 13
2  2  6 10 14
3  3  7 11 15
4  4  8 12 16
[1] "Modified Data Frame"
  C1  C2    C3        C4
1   1   5     9        13
2   2   6    10        14
3   3   7    11        15
4   4   8    12        16
5 New Row Added Dataframe

方法二:

我们可以计算数据框中的行数,然后在索引处添加一个新行(行数 + 1)。可以以值向量的形式定义新行。所做的修改保留在数据框中。这种方法的时间复杂度与行大小呈线性关系。以下代码片段指示了此方法的用法:

电阻

# declaring a data frame in R
data_frame = data.frame(C1 = c(1:4),
                        C2 = c( 5:8), 
                        C3 = c(9:12),
                        C4 = c(13:16))
  
print("Original data frame")
print(data_frame)
  
# calculating number of rows in data frame
num_rows = nrow(data_frame)
  
# defining new row data frame
new_row = c("New","Row","Added","Dataframe")
  
# assigning the new row at a new
# index after the original number of rows 
data_frame[num_rows + 1,] = new_row
print ("Modified Data Frame")
print(data_frame)

输出:

[1] "Original data frame"
 C1 C2 C3 C4
1  1  5  9 13
2  2  6 10 14
3  3  7 11 15
4  4  8 12 16
[1] "Modified Data Frame"
  C1  C2    C3        C4
1   1   5     9        13
2   2   6    10        14
3   3   7    11        15
4   4   8    12        16
5 New Row Added Dataframe