1
這裏是我想的名字的性別編碼隨着時間的推移一些樣本數據:傳承ddply分裂的當前值功能
names_to_encode <- structure(list(names = structure(c(2L, 2L, 1L, 1L, 3L, 3L), .Label = c("jane", "john", "madison"), class = "factor"), year = c(1890, 1990, 1890, 1990, 1890, 2012)), .Names = c("names", "year"), row.names = c(NA, -6L), class = "data.frame")
這裏是一個集社會保障數據的最小的,有限的只是那些從1890年和1990年的名字:
ssa_demo <- structure(list(name = c("jane", "jane", "john", "john", "madison", "madison"), year = c(1890L, 1990L, 1890L, 1990L, 1890L, 1990L), female = c(372, 771, 56, 81, 0, 1407), male = c(0, 8, 8502, 29066, 14, 145)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), .Names = c("name", "year", "female", "male"))
我定義其子集給出的年一年或範圍的社會保障數據的功能。換句話說,它通過計算男性和女性的出生比例以及這個名字來計算某個特定時間段的名字是男性還是女性。這裏是一個輔助功能沿功能:
require(plyr)
require(dplyr)
select_ssa <- function(years) {
# If we get only one year (1890) convert it to a range of years (1890-1890)
if (length(years) == 1) years <- c(years, years)
# Calculate the male and female proportions for the given range of years
ssa_select <- ssa_demo %.%
filter(year >= years[1], year <= years[2]) %.%
group_by(name) %.%
summarise(female = sum(female),
male = sum(male)) %.%
mutate(proportion_male = round((male/(male + female)), digits = 4),
proportion_female = round((female/(male + female)), digits = 4)) %.%
mutate(gender = sapply(proportion_female, male_or_female))
return(ssa_select)
}
# Helper function to determine whether a name is male or female in a given year
male_or_female <- function(proportion_female) {
if (proportion_female > 0.5) {
return("female")
} else if(proportion_female == 0.5000) {
return("either")
} else {
return("male")
}
}
現在我想要做的就是使用plyr,具體ddply
,以子集逐年編碼的數據,並用返回的值合併的每個那件由select_ssa
功能。這是我的代碼。
ddply(names_to_encode, .(year), merge, y = select_ssa(year), by.x = "names", by.y = "name", all.x = TRUE)
當調用select_ssa(year)
,這個命令的作品就好了,如果我硬編碼像1890
作爲參數傳遞給函數的值。但是,當我試圖通過它year
是ddply
正在與當前值,我得到一個錯誤信息:
Error in filter_impl(.data, dots(...), environment()) :
(list) object cannot be coerced to type 'integer'
如何傳遞的year
當前值上ddply
?
這很好,適用於這些數據集。我的困難是我正在爲R包寫這個,所以我不能假設名字列被命名爲'name',年份列在用戶數據中被命名爲'year'。在之前的question中,我瞭解到dplyr不允許您指定要加入的列。我應該強制用戶重命名列嗎? –
@LincolnMullen你可以使用'regroup'以編程方式在dplyr中進行分組,如果有幫助的話。請參閱[這裏](http://stackoverflow.com/q/21815060/324364)。 – joran