在R中,我正在尝试根据唯一ID聚合数据帧,但我需要为ID使用某种通配符值。意思是我有这样的配对名称:
lion_tiger
elephant_lion
tiger_lion
我需要将lion_tiger和tiger_lion ID汇总在一起,因为该对中的顺序并不重要。
以此数据框为例:
df <- data.frame(pair = c("1_3","2_4","2_2","1_2","2_1","4_2","3_1","4_3","3_2"),
value = c("12","10","19","2","34","29","13","3","14"))
因此,对ID,“1_2”和“2_1”的值需要在新表中求和。然后,新行将显示为:
1_2 36
有什么建议吗?虽然我的示例将数字作为对ID,但实际上我需要这样才能读取文本(例如上面的lion_tiger“例子)。
答案 0 :(得分:3)
我们可以将{pair}列拆分为_
,然后将sort
和paste
拆分回来,按功能分组使用它来获取sum
tapply(as.numeric(as.character(df$value)),
sapply(strsplit(as.character(df$pair), '_'), function(x)
paste(sort(as.numeric(x)), collapse="_")), FUN = sum)
或另一个选项是gsubfn
library(gsubfn)
df$pair <- gsubfn('([0-9]+)_([0-9]+)', ~paste(sort(as.numeric(c(x, y))), collapse='_'),
as.character(df$pair))
df$value <- as.numeric(as.character(df$value))
aggregate(value~pair, df, sum)
答案 1 :(得分:1)
使用tidyverse和purrrlyr
df <- data.frame(name=c("lion_tiger","elephant_lion",
"tiger_lion"),value=c(1,2,3),stringsAsFactors=FALSE)
require(tidyverse)
require(purrrlyr)
df %>% separate(col = name, sep = "_", c("A", "B")) %>%
by_row(.collate = "rows",
..f = function(this_row) {
paste0(sort(c(this_row$A, this_row$B)), collapse = "_")
}) %>%
rename(sorted = ".out") %>%
group_by(sorted) %>%
summarize(sum(value))%>%show
## A tibble: 2 x 2
# sorted `sum(value)`
# <chr> <dbl>
#1 elephant_lion 2
#2 lion_tiger 4