简体   繁体   English

汇总数据框

[英]Summary a data frame

I have the following database. 我有以下数据库。 How can I ignore the empty cell and compress into one row ?? 如何忽略空单元格并压缩成一行?

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)

Thank You 谢谢

As @Nicola already expressed in the comments: 正如@Nicola在评论中已经表达的那样:

M2 <- aggregate(.~Name, M, paste, collapse="")

is giving the desired output: 提供所需的输出:

> M2
  Name Col1 Col2
1 name    1    2

您可以使用聚合函数来解决您的问题。

aggregate(M[c("Col1","Col2")], list(M$Name), max, na.rm = TRUE)

Here is a dplyr solution 这是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

This works based on the input data without having to convert the columns to characters 这基于输入数据而无需将列转换为字符

M = data.frame( Name = c('name','name'), Col1 = c("",1) , Col2 = c(2,""))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM