R:在调用rbind()时控制自动创建的列名

las*_*owh 3 r

如果我做这样的事情:

> df <- data.frame()
> rbind(df, c("A","B","C"))
  X.A. X.B. X.C.
1    A    B    C
Run Code Online (Sandbox Code Playgroud)

您可以看到该行被添加到空数据框中.但是,列会根据数据的内容自动命名.

如果我以后想要这会导致问题:

> df <- rbind(df, c("P", "D", "Q"))
Run Code Online (Sandbox Code Playgroud)

有没有办法控制由rbind自动创建的列的名称?或者其他一些方法来做我在这里尝试做的事情?

Tom*_*mmy 8

@ baha-kev对字符串和因素有一个很好的答案.

我只是想指出rbinddata.frame 的奇怪行为:

# This is "should work", but it doesn't:
# Create an empty data.frame with the correct names and types
df <- data.frame(A=numeric(), B=character(), C=character(), stringsAsFactors=FALSE)
rbind(df, list(42, 'foo', 'bar')) # Messes up names!
rbind(df, list(A=42, B='foo', C='bar')) # OK...

# If you have at least one row, names are kept...
df <- data.frame(A=0, B="", C="", stringsAsFactors=FALSE)
rbind(df, list(42, 'foo', 'bar')) # Names work now...
Run Code Online (Sandbox Code Playgroud)

但是,如果你只有字符串,那么为什么不使用矩阵呢?然后它可以从一个空矩阵开始工作正常:

# Create a 0x3 matrix:
m <- matrix('', 0, 3, dimnames=list(NULL, LETTERS[1:3]))

# Now add a row:
m <- rbind(m, c('foo','bar','baz')) # This works fine!
m

# Then optionally turn it into a data.frame at the end...
as.data.frame(m, stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)