Select 数据框中的下一行以便在 R 中插入数据

Select next row in dataframe in order to insert data in R

我有一个数据框,例如:

   name    age
1 "Danny"  20
2 "Mitt"   35
3 "Dylan"  8

当我获得新条目时,我想更新此 df。 我在下一行使用了 nrow(df) + 1

df[nrow(df) + 1, ] <- c("Tom", 4)

还有其他方法吗?

您可以使用 rbind:

rbind(df,list("Tom",4))

检查 ?rbind:

The functions cbind and rbind are S3 generic, with methods for data frames. The data frame method will be used if at least one argument is a data frame and the rest are vectors or matrices. There can be other methods; in particular, there is one for time series objects. See the section on ‘Dispatch’ for how the method to be used is selected. If some of the arguments are of an S4 class, i.e., isS4(.) is true, S4 methods are sought also, and the hidden cbind / rbind functions from package methods maybe called, which in turn build on cbind2 or rbind2, respectively. In that case, deparse.level is obeyed, similarly to the default method.

In the default method, all the vectors/matrices must be atomic (see vector) or lists. Expressions are not allowed. Language objects (such as formulae and calls) and pairlists will be coerced to lists: other objects (such as names and external pointers) will be included as elements in a list result. Any classes the inputs might have are discarded (in particular, factors are replaced by their internal codes).

If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. If all the arguments are vectors, the number of columns (rows) in the result is equal to the length of the longest vector. Values in shorter arguments are recycled to achieve this length (with a warning if they are recycled only fractionally).

让我向您推荐 tibble 包中的 add_row 函数。您可以简单地按照以下方式进行操作:

df = add_row (df, name="Tom", age=4)