我正在尝试将两行数据合并为一行聚合数据。两行中的大部分值是相同的。如果它们不同,我想将数据附加在一起。
我首先使用
add_row()
创建一个新的空白行,该行将作为聚合数据的目标(包含所有 NA
值)。然后,我尝试编写一个调用来评估每个字段中两行的内容。如果它们相同,则会将该值填充到添加的空白行中。如果它们不相同,它们会用分隔符将这些值连接在一起。
我能够获取代码来根据其他值评估列中的每个值并返回我想要的输出,但它覆盖了原始两行中的现有值,并且没有填充到我创建的空白第三行中。这就是我陷入困境的地方,我不确定如何引导代码将聚合值填充到创建的行的空白单元格中。
我不愿意旋转我的数据来创建一个新列来填充,然后再将其旋转回来,因为我不想丢失我的 ID 字段(而且我也永远不擅长旋转),但这可能是解决方案,除非有更优雅的方法。
如有任何建议,我们将不胜感激。谢谢!
# Sample Data
library(tidyverse)
test<-data.frame("ID"=c("1","2"),
"Email"=c("[email protected]","[email protected]"),
"Gender"=c("Female","Female"),
"Location"=c("Los Angeles","Los Angeles"),
"Ice_Cream_Flavor"=c("Strawberry","Rocky Road"))
## Original Table
# A tibble: 2 × 5
ID Email Gender Location Ice_Cream_Flavor
<chr> <chr> <chr> <chr> <chr>
1 1 [email protected] Female Los Angeles Strawberry
2 2 [email protected] Female Los Angeles Rocky Road
## Attempted Code
merge<-test%>%
add_row()%>% # creating a new blank row to populate with aggregated data
mutate(across(.cols = -c(`ID`,
`Email`), # calling up all columns except these specific ones
~ case_when(!is.na(`ID`) & .[1]==.[2] ~ .[1], # Checking for equality in the values and returning the value in the first row
!is.na(`ID`) & .[1]!=.[2] ~ paste(.[1],.[2], sep = "; "), # appending unequal values together
TRUE~NA)))
## Output
# A tibble: 3 × 5
ID Email Gender Location Ice_Cream_Flavor
<chr> <chr> <chr> <chr> <chr>
1 1 [email protected] Female Los Angeles Strawberry; Rocky Road
2 2 [email protected] Female Los Angeles Strawberry; Rocky Road
3 NA NA NA NA NA
我不是 100% 清楚结果应该是什么样子,但下面的代码使用
summarise()
来组合 2 行,并使用 bind_rows()
将其添加到原始数据中:
library(tidyverse)
test<-data.frame("ID"=c("1","2"),
"Email"=c("[email protected]","[email protected]"),
"Gender"=c("Female","Female"),
"Location"=c("Los Angeles","Los Angeles"),
"Ice_Cream_Flavor"=c("Strawberry","Rocky Road"))
# Helper function to use in summarise
combine <- function(a) {
if(a[1] == a[2]) {
a[1]
} else {
paste(a[1], a[2], sep = "; ")
}
}
# add the summarised row to your original data
merge <- test %>%
bind_rows(
summarise(test, across(-c(ID, Email), combine))
)
merge
ID Email Gender Location Ice_Cream_Flavor
1 1 [email protected] Female Los Angeles Strawberry
2 2 [email protected] Female Los Angeles Rocky Road
3 <NA> <NA> Female Los Angeles Strawberry; Rocky Road