首页 > 解决方案 > rbind several columns of one data frame below each other

问题描述

I have a df in which several features describe one word. For further analysis I need all features below each other, including the described word. I guess an example will make it easier to understand:

df <- data.frame(a = c(1:4), feature1 = c("word1", "word2", "word3", "word4"), feature2 = c("a", "b", "c", "d"), inputword = c("this", "that", "this2", "that2"))
df

  a feature1 feature2 inputword
1 1    word1        a      this
2 2    word2        b      that
3 3    word3        c     this2
4 4    word4        d     that2

Now I would need every feature in one column including the inputword info and a. Expected output:

  a feature2 inputword
1 1    word1      this
2 2    word2      that
3 3    word3     this2
4 4    word4     that2
5 1        a      this
6 2        b      that
7 3        c     this2
8 4        d     that2

I found a way to get to my expected output by creating single dataframe and then rbind.data.frame them. However in the original data set I have up to 18 features, so creating single data frames like below seems very inefficient.

The way I made it worked:

df1 <- df[ , -c(3)]
df2 <- df[ , -c(2)]
colnames(df1)=colnames(df2)
df_all <- rbind.data.frame(df1, df2)
df_all

  a feature2 inputword
1 1    word1      this
2 2    word2      that
3 3    word3     this2
4 4    word4     that2
5 1        a      this
6 2        b      that
7 3        c     this2
8 4        d     that2

Maybe someone can help me with a more efficient way to get what I want?

Thank you in advance!

标签: r

解决方案


Here is a data.table option using melt

> melt(setDT(df), id.var = c("a", "inputword"), value.name = "feature")[, .(a, feature, inputword)]
   a feature inputword
1: 1   word1      this
2: 2   word2      that
3: 3   word3     this2
4: 4   word4     that2
5: 1       a      this
6: 2       b      that
7: 3       c     this2
8: 4       d     that2

推荐阅读