将特定索引位置的新行添加到 R 中的数据帧
在本文中,我们将讨论如何使用 R 编程语言在数据帧的特定索引处添加新行。
这里的主要任务是移动其他行并在数据框中为新行腾出空间,然后插入其内容。这可以通过两种方式完成
方法一:使用 rbind()
R 语言中的rbind()函数用于按行组合指定的 Vector、Matrix 或 Data Frame。
Syntax: rbind(x1, x2, …, deparse.level = 1)
Parameters:
- x1, x2: vector, matrix, data frames
- deparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
例子
R
rm(list = ls())
# Function to create new dataframe
insertRow <- function(data, new_row, r) {
data_new <- rbind(data[1:r, ],
new_row,
data[- (1:r), ])
rownames(data_new) <- 1:nrow(data_new)
return(data_new)
}
existingDF <- data.frame(x1 = c(15,25,35,45,55),
x2 = c(23,34,45,56,76),
x3 = c(12,23,3,454,26))
index <- 4
newrow <- c(9, 99, 999)
newDF=insertRow(existingDF, newrow, index)
print(newDF)
R
rm(list = ls())
# Function to create new dataframe
insertRow <- function(existingDF, new_row, r) {
existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
existingDF[r,] <- new_row
return(existingDF)
}
existingDF <- data.frame(x1 = c(1,7,13,25,31),
x2 = c(2,8,14,26,32),
x3 = c(3,9,15,27,33),
x4 = c(4,10,16,28,34),
x5 = c(5,11,17,29,35),
x6 = c(6,12,18,30,36))
r <- 4
new_row <- c(19,20,21,22,23,24)
newDF=insertRow(existingDF, new_row, r)
print(newDF)
输出:
方法 2:使用 seq()
另一种方法是使用 seq()函数。这里的方法是相同的,但方法有些不同。我们正在访问数据帧的行并在其中创建空间。此外,我们使用 nrows() 来计算总行数。
R 语言中的seq()函数用于在 Vector 中创建元素序列。它将长度和值之间的差异作为可选参数。
Syntax: seq(from, to, by, length.out)
Parameters:
- from: Starting element of the sequence
- to: Ending element of the sequence
- by: Difference between the elements
- length.out: Maximum length of the vector
例子:
电阻
rm(list = ls())
# Function to create new dataframe
insertRow <- function(existingDF, new_row, r) {
existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
existingDF[r,] <- new_row
return(existingDF)
}
existingDF <- data.frame(x1 = c(1,7,13,25,31),
x2 = c(2,8,14,26,32),
x3 = c(3,9,15,27,33),
x4 = c(4,10,16,28,34),
x5 = c(5,11,17,29,35),
x6 = c(6,12,18,30,36))
r <- 4
new_row <- c(19,20,21,22,23,24)
newDF=insertRow(existingDF, new_row, r)
print(newDF)
输出: