【问题标题】:Combine contents in different columns into one column将不同列中的内容合并为一列
【发布时间】:2021-12-28 21:33:29
【问题描述】:

亲爱的堆栈溢出天才,

我正在尝试将包含 10 列的 data.frame 合并为 1 列,然后删除重复项。现在我正在以一种愚蠢的方式进行操作,有人可以告诉我如何循环吗?抱歉,我对 R 很陌生。非常感谢!

数据很简单,这里只是一个例子

C1 c2 c3 c4 c5 c6 c7 c8 c9 c10
13 16 19 1 20 36 8 22 10 20
15 20 16
col1 <- as.character(allcol[,1])
col2 <- as.character(allcol[,2])
col3 <- as.character(allcol[,3])
col4 <- as.character(allcol[,4])
col5 <- as.character(allcol[,5])
col6 <- as.character(allcol[,6])
col7 <- as.character(allcol[,7])
col8 <- as.character(allcol[,8])
col9 <- as.character(allcol[,9])
col10 <- as.character(allcol[,10])
allcol <- c(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10)`
uniqueallcol <- unique(allcol)

【问题讨论】:

  • 非常感谢您的编辑

标签: r loops multiple-columns


【解决方案1】:

如果所有列都具有相同的数据类型(例如数字),您可以使用 unlist 将数据框转换为单个向量,使用 unique 删除结果向量中的重复项,然后将其转回进入带有data.frame的数据框:

uniqueallcol <- data.frame("unique_col" = unique(unlist(allcol)))

【讨论】:

  • 非常感谢!效果很好!
猜你喜欢
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 2018-07-05
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
相关资源
最近更新 更多