R-将多行彼此并排连接 [英] R - concatenate multiple rows into one beside each other
问题描述
我有一个3列多行的数据框.我想拆分数据框,以使只有一行,并且值是按顺序排列的(因此本质上是一行csv).
I have a dataframe with 3 columns and multiple rows. I want to split up the dataframe so that there is only one row and the values are in sequence (so essentially a one row csv).
我的数据框如下:
**Subject Module ID**
History WW2 1
English Literature 2
Maths Algebra 3
我想要实现的是一行,看起来像这样,并按此顺序排列:
What I am trying to achieve is one row that will look like this and in this order:
History, WW2, 1, English, Literature, 2, Maths, Algebra, 3
我可以使用excel剪切粘贴,但我想知道是否有使用R的快速方法.
I can do it with cut and paste using excel but was wondering was there a quick method with R.
任何帮助都会很棒!谢谢.
Any help would be great! Thanks.
推荐答案
使用 paste
和 collapse
进行此操作. unlist
在您的数据框中创建一个矢量,但是它是按列进行的,因此您需要先 t
对其进行转置.
Use paste
with collapse
to do this. unlist
creates a single vector out of your dataframe, but it does it by column, so you need a t
to transpose it first.
df <- read.table(textConnection("Subject Module ID
History WW2 1
English Literature 2
Maths Algebra 3"),
stringsAsFactors=FALSE, header=TRUE)
> paste(unlist(t(df)), collapse=",")
[1] "History,WW2,1,English,Literature,2,Maths,Algebra,3"
已编辑以添加您在注释中要求的数据框版本...
edited to add the dataframe version you asked for in the comment...
df1 <- read.csv(text=paste(unlist(t(df)), collapse=","), header=FALSE,
stringsAsFactors=FALSE)
names(df1) <- rep(names(df), nrow(df))
> df1
Subject Module ID Subject Module ID Subject Module ID
1 History WW2 1 English Literature 2 Maths Algebra 3
这会导致列名不唯一,这实际上是不明智的.
This makes non-unique column names, which is not really advisable.
这篇关于R-将多行彼此并排连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!