在 R 中汇总数据框中的“字符”信息,类似于 Excel 数据透视,没有重复项和数字

问题描述 投票:0回答:1

我正在尝试获得与 Excel 数据透视表相同的功能。其中我们有一个巨大的数据集,但它显示了唯一的值,没有重复,并且仅针对文本,如下所示。

我尝试使用

Summarise()
reframe()
但我没有得到理想的解决方案。

我编写的代码如下:

    library(readxl)
    Book1 <- read_excel("C:/Users/X/X- X X/Desktop/Book1.xlsx")
    
    X <- Book1 %>%
      reframe(Country,Group,Name)

附件是我正在使用的数据框:

structure(list(Country = c("France", "France", "France", "France", 
"Germany", "Germany", "Germany", "Germany"), Group = c("Female", 
"Female", "Female", "Male", "Male", "Male", "Male", "Female"), 
    Name = c("Grace", "Steph", "Tiff", "John", "Luca", "Andre", 
    "Reus", "Alica")), row.names = c(NA, -8L), class = c("tbl_df", 
"tbl", "data.frame"))

这是我从 Excel Pivot 获得的预期输出。你能告诉我我做错了什么以及如何纠正吗?抱歉显示图像,但我觉得这会更容易理解。

r excel dataframe pivot
1个回答
0
投票

不确定您可能需要什么,但您可以做

> dat[sapply(1:3, \(i) duplicated(Reduce(paste, dat[seq_len(i)])))] <- ''
> dat
  Country  Group  Name
1  France Female Grace
2                Steph
3                 Tiff
4           Male  John
5 Germany   Male  Luca
6                Andre
7                 Reus
8         Female Alica
© www.soinside.com 2019 - 2024. All rights reserved.