在R中,一旦数据帧初始化,如何向数据帧添加新行?
到目前为止我有这个:
df<-data.frame("hi","bye")
names(df)<-c("hello","goodbye")
#I am trying to add hola and ciao as a new row
de<-data.frame("hola","ciao")
merge(df,de) #adds to the same row as new columns
#I couldnt find an rbind solution that wouldnt give me an error
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
Par*_*ait 104
就像@Khashaa和@Richard Scriven在评论中指出的那样,你必须为你想要追加的所有数据框设置一致的列名.
因此,您需要显式声明第二个数据框的列名de,然后使用rbind().您只需为第一个数据框设置列名df:
df<-data.frame("hi","bye")
names(df)<-c("hello","goodbye")
de<-data.frame("hola","ciao")
names(de)<-c("hello","goodbye")
newdf <- rbind(df, de)
Run Code Online (Sandbox Code Playgroud)
Mat*_*ujo 73
让我们简单一点:
df[nrow(df) + 1,] = c("v1","v2")
Run Code Online (Sandbox Code Playgroud)
根据评论编辑.__CODE__代替__CODE__在添加混合类行的情况下防止类更改.
小智 12
我喜欢list而不是c因为它更好地处理混合数据类型.在原始海报的问题中添加其他列:
#Create an empty data frame
df <- data.frame(hello=character(), goodbye=character(), volume=double())
de <- list(hello="hi", goodbye="bye", volume=3.0)
df = rbind(df,de, stringsAsFactors=FALSE)
de <- list(hello="hola", goodbye="ciao", volume=13.1)
df = rbind(df,de, stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)
请注意,如果字符串/因子转换很重要,则需要一些额外的控制.
或者使用MatheusAraujo/Ytsen de Boer解决方案的原始变量:
df[nrow(df) + 1,] = list(hello="hallo",goodbye="auf wiedersehen", volume=20.2)
Run Code Online (Sandbox Code Playgroud)
请注意,除非数据框中存在现有数据,否则此解决方案不能很好地处理字符串.
J. *_*in. 10
不是非常优雅,但是:
data.frame(rbind(as.matrix(df), as.matrix(de)))
Run Code Online (Sandbox Code Playgroud)
从rbind功能文档:
对于
rbind列名称,从第一个参数中获取适当的名称:矩阵的colnames ...
Joe*_*Joe 10
现在有add_row()来自tibble或tidyverse包。
library(tidyverse)
df %>% add_row(hello = "hola", goodbye = "ciao")
Run Code Online (Sandbox Code Playgroud)
未指定的列会显示NA。