根据数据帧子集以及数据帧列传递函数以在R中进行传输

时间:2016-03-01 18:18:39

标签: r

请考虑以下数据框

#build sample data.frame
theData <- data.frame(surname = c("Smith","Parker", "Allen", "McGraw", "Parker", "Smith", "Smith"),
                     FamilySize = c(3, 2, 1, 1, 2, 3, 3))

首先,我需要确认共享相同姓氏的人数与他们所属家庭的人数相对应。例如,有3个人surname = "Smith",每个FamilySize变量为3.如果满足此条件,则将姓氏附加到姓氏(例如{{1} });如果不是,结果应该是单词"3Smith"

为此,我写了这个函数:

"small"

所以如果我按如下方式调用此函数

# function
familyKount <- function(df, lastName, famSize){
    # calculate number of persons sharing same surname
    nPersons <- dim(subset(df, surname == lastName))[1]

    # number of persons agrees with family size
    if(nPersons == famSize) {
            idFam <- paste(as.character(famSize), lastName, sep="")
    } else {                # number of persons does not agree with family size
            idFam <- "small"
    }
    idFam
}

我得到了正确答案:familyKount(theData, theData$surname[1], theData$FamilySize[1])

但是,我想要的是将此函数应用于整个数据框,而不必为"3Smith"surname指定索引(我不想使用{{1循环)。我已经尝试了FamilySize函数族的变体,但我还没有弄清楚如何在这种情况下将整个数据框及其特定列作为函数的参数传递。

干杯

1 个答案:

答案 0 :(得分:1)

有很多解决方案。例如,您可以使用表格:

wb

With wb.Worksheets(1).Range("A1")

table(theData$surname)

##  Allen McGraw Parker  Smith 
##      1      1      2      3 

dplyr

library(dplyr)
group_by(theData, surname) %>%
  summarize(SizeCalculated = n()
## Source: local data frame [4 x 2]
## 
##   surname SizeCalculated
##    (fctr)          (int)
## 1   Allen              1
## 2  McGraw              1
## 3  Parker              2
## 4   Smith              3)

您还可以找到aggregate()的解决方案,该解决方案可能类似于您的预期:

aggregate(theData, list(theData$surname), length)
##   Group.1 surname FamilySize
## 1   Allen       1          1
## 2  McGraw       1          1
## 3  Parker       2          2
## 4   Smith       3          3

这个想法是适用于姓氏。

所有这些解决方案都可以扩展为包括sapply()来自surnames <- unique(theData$surname) counts <- sapply(surnames, function(s) sum(theData$surname == s)) data.frame(surnames, counts) ## surnames counts ## 1 Smith 3 ## 2 Parker 2 ## 3 Allen 1 ## 4 McGraw 1 的检查。例如,FamilySize - 解决方案:

theData