r - 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!
解决方案
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
推荐阅读
- python - 如何从字典中仅提取某些值(python)
- python - 如何在 pex 文件中使用 ubuntu 包
- javascript - 将 JSON 转换为 ANY 类型的 TW 对象
- angular - 社交登录 - 权限
- firebase - 在 Unity 中集成 Firebase 后无法在 Android 设备上运行
- python - 在 pandas 数据框中使用 bin
- redis - Redis集群无法添加节点
- selenium - Selenium 节点与网格断开连接
- hybris - Hybris:内容页面、类别页面和产品页面之间的区别
- android - Android/iOS 应用程序未检测到由 iOS/Android 应用程序索引的人脸 - AWS Rekognition