【问题标题】:Splitting dataframe and keeping shared columns拆分数据框并保留共享列
【发布时间】:2018-05-11 18:40:42
【问题描述】:

我有一个数据框

df = data.frame(V1 = 1, V2 = 2, V3 = 3, V4 = 4, V5 = 5, respondent_ID = "ID1", respondent_attribute = "Attribute1")

并希望将其拆分为两个数据帧,其中一个将包含列 V1、V2、V3、respondent_ID 和 respondent_attribute,另一个将包含 V4、V5、respondent_ID 和 respondent_attribute。

我可以相对轻松地做到这一点

newdf <- subset(df, select = c(1:3, 6:7))

然后从 df 中手动删除列 V1、V2 和 V3

df[1:3] = NULL

但我怀疑有一个更优雅(也许是更好的做法)的解决方案。有什么建议吗?

【问题讨论】:

  • 您可以只使用df[,c(1,2,3,6,7)]df[,c("V1","V2","V3","respondent_ID","respondent_attribute")] 形式(第二个类似),具体取决于您是否知道列索引

标签: r dataframe dplyr


【解决方案1】:

如果你这样做,你可以有更好的控制:

df = data.frame(V1 = 1, V2 = 2, V3 = 3, V4 = 4, V5 = 5, respondent_ID = "ID1", respondent_attribute = "Attribute1")

# Alternative 1
newdf1 <- df[,c("V1", "V2", "V3", "respondent_ID", "respondent_attribute")]
newdf2 <- df[,c("V4", "V5", "respondent_ID", "respondent_attribute")]

# Alternative 2
newdf1 <- df[,c(1:3, 6:7)]
newdf2 <- df[,c(4:5, 6:7)]

希望对您有所帮助! :)

【讨论】:

  • 我想这是有道理的。您的方法也适用于 newdf1 &lt;- df[,c(1:3, 6:7)],这对于处理大型数据帧很有用。
猜你喜欢
  • 2022-12-09
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 2017-12-24
相关资源
最近更新 更多