我有以下数据库。 如何忽略空单元格并压缩成一行?
M = data.frame( Name = c('name','name'), Col1 = c("",1) , Col2 = c(2,""))
M$Col1 <- as.character(M$Col1)
M$Col2 <- as.character(M$Col2)
谢谢
答案 0 :(得分:1)
As @Nicola already expressed in the comments:
M2 <- aggregate(.~Name, M, paste, collapse="")
is giving the desired output:
> M2
Name Col1 Col2
1 name 1 2
答案 1 :(得分:0)
您可以使用聚合功能来解决您的问题。
aggregate(M[c("Col1","Col2")], list(M$Name), max, na.rm = TRUE)
答案 2 :(得分:0)
这是dplyr
解决方案
library(dplyr)
M %>%
group_by(Name) %>%
summarise(Col1 = paste0(Col1, collapse = ''),
Col2 = paste0(Col2, collapse = ''))
## Name Col1 Col2
## (fctr) (chr) (chr)
## 1 name 1 2
这基于输入数据而不必将列转换为字符
M = data.frame( Name = c('name','name'), Col1 = c("",1) , Col2 = c(2,""))