让 rbind 忽略列名的最简单方法 [英] Simplest way to get rbind to ignore column names

查看:163
本文介绍了让 rbind 忽略列名的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是为了回答这里的另一个问题.当您rbind 两个数据框时,它会按名称而不是索引匹配列,这可能会导致意外行为:

This came up just in an answer to another question here. When you rbind two data frames, it matches columns by name rather than index, which can lead to unexpected behavior:

> df<-data.frame(x=1:2,y=3:4)
> df
  x y
1 1 3
2 2 4
> rbind(df,df[,2:1])
  x y
1 1 3
2 2 4
3 1 3
4 2 4

当然,有解决方法.例如:

Of course, there are workarounds. For example:

rbind(df,rename(df[,2:1],names(df)))
data.frame(rbind(as.matrix(df),as.matrix(df[,2:1])))

编辑时:plyr 包中的 rename 实际上并不是这样工作的(虽然我在最初写这个的时候以为我已经工作了......).重命名的方法是使用SimonO101的解决方案:

On edit: rename from the plyr package doesn't actually work this way (although I thought I had it working when I originally wrote this...). The way to do this by renaming is to use SimonO101's solution:

rbind(df,setNames(df[,2:1],names(df)))

另外,也许令人惊讶的是,

Also, maybe surprisingly,

data.frame(rbindlist(list(df,df[,2:1])))

按索引工作(如果我们不介意数据表,那么它非常简洁),所以这是 do.call(rbind) 之间的区别.

works by index (and if we don't mind a data table, then it's pretty concise), so this is a difference between do.call(rbind).

问题是,rbind 两个名称不匹配的数据框的最简洁方法是什么?我知道这看起来微不足道,但这种事情最终会导致代码混乱.而且我不想编写一个名为 rbindByIndex 的新函数.理想情况下,它类似于 rbind(df,df[,2:1],byIndex=T).

The question is, what is the most concise way to rbind two data frames where the names don't match? I know this seems trivial, but this kind of thing can end up cluttering code. And I don't want to have to write a new function called rbindByIndex. Ideally it would be something like rbind(df,df[,2:1],byIndex=T).

推荐答案

您可能会发现 setNames 在这里很方便...

You might find setNames handy here...

rbind(df, setNames(rev(df), names(df)))
#  x y
#1 1 3
#2 2 4
#3 3 1
#4 4 2

我怀疑您的实际用例要复杂一些.您当然可以根据需要重新排序 setNames 的第一个参数中的列,只需在第二个参数中使用 names(df) ,以便重新排序的列的名称匹配原来的.

I suspect your real use-case is somewhat more complex. You can of course reorder columns in the first argument of setNames as you wish, just use names(df) in the second argument, so that the names of the reordered columns match the original.

这篇关于让 rbind 忽略列名的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆