R - 函数像COUNTIFS

时间:2018-02-07 15:27:21

标签: r excel data-manipulation

我正在寻找R&C的版本的Excel" COUNTIFS"功能

情景:

  

我有两列完整的值,我想添加一个存储的列   Col1和Col2中具有相同值的记录数

这就像必须将主键拆分为两列我猜

Col1 Col2 Col3 ColNew
A1   B1   EPP  2
A1   B2   EPP  1
A1   B1   EPP  2

在Excel中,我使用以下公式

开始工作
  

= COUNTIFS(C:C,$ C2,A:A,$ A2,E:E,$ E $ 2)→1

但实际上它返回TRUEFALSE而不是数字

有什么想法吗?

5 个答案:

答案 0 :(得分:6)

在这种情况下,

ave可能是一个非常有用的功能:

df$ColNew <- ave(rep(1, nrow(df)), df$Col1, df$Col2, FUN = length)

df
#  Col1 Col2 Col3 ColNew
#1   A1   B1  EPP      2
#2   A1   B2  EPP      1
#3   A1   B1  EPP      2

答案 1 :(得分:5)

dplyrdata.table是两个流行的套餐,可以“轻松地”按小组进行操作。

使用dplyr

df %>% group_by(Col1, Col2) %>% mutate(ColNew = n())

使用data.table

setDT(df)
df[, ColNew := .N, by = .(Col1, Col2)]

答案 2 :(得分:4)

transform(dat,col=ave(do.call(paste,dat),Col2,Col3,FUN = length))
  Col1 Col2 Col3 col
1   A1   B1  EPP   2
2   A1   B2  EPP   1
3   A1   B1  EPP   2

答案 3 :(得分:3)

dplyr有一个名为add_count的函数可以执行此操作:

library(dplyr)
df %>%
  group_by(Col1,Col2) %>%
  add_count

# # A tibble: 3 x 4
# # Groups:   Col1, Col2 [2]
#    Col1  Col2  Col3     n
#   <chr> <chr> <chr> <int>
# 1    A1    B1   EPP     2
# 2    A1    B2   EPP     1
# 3    A1    B1   EPP     2

数据

df <- read.table(text="Col1 Col2 Col3
A1   B1   EPP
A1   B2   EPP
A1   B1   EPP",header=TRUE,stringsAsFactors=FALSE)

答案 4 :(得分:1)

假设您的数据框为df,请尝试:

library(plyr)
counts <- ddply(df, .(df$Col1, df$Col2), nrow)
names(counts) <- c("Col1", "Col2", "Freq")

请你试试这个替代解决方案:

library(data.table)
dt <- data.table(df)
dt[, list(Freq =.N), by=list(Col1,Col2)]

根据问题中提供的数据,我期待结果集如下:

Col1 Col2 Freq
A1   B1   2
A1   B2   1