如何在不同表的列中创建具有一定数量的发生次数的新列?

时间:2019-04-10 23:11:54

标签: r

我有两个数据框:“家庭”和“个人”。

这是“家庭”:

structure(list(ID = 1:5), class = "data.frame", row.names = c(NA, 
-5L))

这是“个人”:

structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 
3L, 4L, 4L, 4L, 4L, 5L, 5L), Yesno = c(1L, 0L, 1L, 0L, 0L, 0L, 
1L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA, 
-17L))

我正在尝试向住户添加新列,以计算变量Yesno等于1的次数。

我尝试过

households$Count <- as.numeric(ave(individuals$Yesno[individuals$Yesno == 1], households$ID, FUN = count))

家庭应如下所示:

ID  Count
1   2
2   3
3   0
4   2
5   1

2 个答案:

答案 0 :(得分:4)

选项1:以R为基数

使用mergeaggregate

aggregate(Yesno ~ ID, merge(households, individuals), FUN = sum)
#  ID Yesno
#1  1     2
#2  2     3
#3  3     0
#4  4     2
#5  5     1

选项2:使用dplyr

使用left_joingroup_by + summarise

library(dplyr)
left_join(households, individuals) %>%
    group_by(ID) %>%
    summarise(Count = sum(Yesno))
#Joining, by = "ID"
## A tibble: 5 x 2
#     ID Count
#  <int> <int>
#1     1     2
#2     2     3
#3     3     0
#4     4     2
#5     5     1

选项3:使用data.table

library(data.table)
setDT(households)
setDT(individuals)
households[individuals, on = "ID"][, .(Count = sum(Yesno)), by = ID]
#   ID Count
#1:  1     2
#2:  2     3
#3:  3     0
#4:  4     2
#5:  5     1

样本数据

households <- structure(list(ID = 1:5), class = "data.frame", row.names = c(NA,
-5L))

individuals <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L,
3L, 4L, 4L, 4L, 4L, 5L, 5L), Yesno = c(1L, 0L, 1L, 0L, 0L, 0L,
1L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-17L))

答案 1 :(得分:1)

另一种使用sapply的基本R方法是循环ID中的每个households以及IDindividuals的子集,并计算其中有多少Yesno列中为1。

households$Count <- sapply(households$ID, function(x) 
                   sum(individuals$Yesno[individuals$ID == x] == 1))

households
#  ID Count
#1  1     2
#2  2     3
#3  3     0
#4  4     2
#5  5     1

如果== 1列中只有0和1,则可以删除函数中的Yesno部分。