计算另一个数据帧中的行数

时间:2018-06-07 07:59:09

标签: r merge count tidyverse

我有两个数据框df1df2

df1 <- data.frame(id=1:5, var1=c("c3e", "d3r", "ff2", "dfl", "df4"))
df2 <- data.frame(id=1:10, var1=c("d3r", "d3r", "c3e", "dfl", "dfl", "dfl", "c3e", "df4", "c3e", "c3e"))

如何在df1中最好地创建一个新列,在df1$var1中给出df2中每个值的出现次数?例如。 &#39; C3E&#39;出现四次,&#39; d3r&#39;两次等。

3 个答案:

答案 0 :(得分:3)

我们可以遍历df1$var1的每个值,并计算df2 s var1中值的出现次数。

df1$count <- sapply(df1$var1, function(x) sum(df2$var1 %in% x))

df1
#  id var1 count
#1  1  c3e     4
#2  2  d3r     2
#3  3  ff2     0
#4  4  dfl     3
#5  5  df4     1

答案 1 :(得分:2)

df1$count <- table(df2$var1)[df1$var1]
df1$count[is.na(df1$count)] <- 0          # change NA to 0

df1
#   id var1 count
# 1  1  c3e     4
# 2  2  d3r     2
# 3  3  ff2     0
# 4  4  dfl     3
# 5  5  df4     1

@Jaap也提出了一个很好的建议:

df1$count <- table(factor(df2$var1, levels = df1$var1))

答案 2 :(得分:0)

以下是this.router.navigate(['userdetails']);

的一个选项
const routes: Routes = [
  { path: '', component: ResulTabComponent },
  { path: "administration/userdetails", component: UserDisplayComponent }
]