这可能是一个非常简单的答案,但我无法找到解决方案。
我有一个数据框:
structure(list(year = structure(1:23, .Label = c("1990", "1991",
"1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999",
"2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
"2008", "2010", "2011", "2012", "2013"), class = "factor"), val = c(8,
3, 1, 17, 5, 9, 6, 7, 3, 15, 11, 6, 2, 11, 15, 11, 15, 1, 14,
2, 15, 4, 6)), .Names = c("year", "val"), row.names = c(NA, -23L
), class = "data.frame")
我想在2008年到2010年之间手动添加一行(年= 2009年,val = 20)。
我使用Add new row to dataframe, at specific row-index, not appended?执行此操作:
#1
r<-seq(4)
newrow<-c(2009,5)
insertRow <- function(df, newrow, r) {
df[seq(r+1,nrow(df)+1),] <- df[seq(r,nrow(df)),]
df[r,] <- newrow
df
}
insertRow(df, newrow, r)
但我得到了这个:
Error in seq.default(r, nrow(df)) :
'from' must be of length 1
#2
newrow<-c(2009,20)
rbind(df,newrow)
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, :
invalid factor level, NA generated