R: 控件在对rbind()的调用中自动创建的列名

  • 本文关键字:调用 创建 控件 rbind r
  • 更新时间 :
  • 英文 :


如果我这样做:

> df <- data.frame()
> rbind(df, c("A","B","C"))
  X.A. X.B. X.C.
1    A    B    C

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

如果我以后想的话,这会引起问题:

> df <- rbind(df, c("P", "D", "Q"))

有没有一种方法可以控制rbind自动创建的列的名称?或者用其他方式来做我想在这里做的事情?

@baha kev对字符串和因子有一个很好的答案。

我只想指出rbind对data.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...

但如果你只有字符串,为什么不使用矩阵呢?然后从一个空矩阵开始就可以了:

# 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)

将选项"stringsAsFactors"设置为False,将值存储为字符:

df=data.frame(first = 'A', second = 'B', third = 'C', stringsAsFactors=FALSE)
rbind(df,c('Horse','Dog','Cat'))
  first second third
1     A      B     C
2 Horse    Dog   Cat
sapply(df2,class)
      first      second       third 
"character" "character" "character" 

稍后,如果你想使用因子,你可以这样转换:

df2 = as.data.frame(df, stringsAsFactors=T)