我有一系列媒体来源,我必须为其分配县名。对于只有一个县分配的某些来源(例如当地报纸),这相当简单——我基于一个switch
根据来源名称分配县名的函数创建了一个县名变量。样本:
switchfun <- function(x) {switch(x, 'Morning Call' = 'Lehigh', 'Inquirer' =
'Philadelphia', 'Daily Ledger' = 'Mercer', 'Null') }
County.Name <- as.character(lapply(Source, switchfun))
但是我有想分配给数据集中所有县的来源(NPR、AP 等)。这实质上是复制任何来源为“国家”的记录,并将记录分配给我数据集中的每个县。
dput
当前文件布局:
structure(list(Source = structure(c(5L, 2L, 4L, 3L, 7L, 1L, 6L
), .Label = c("Associated Press", "Daily Ledger", "Herald Tribune",
"Inquirer", "Morning Call", "NPR", "Yahoo News"), class = "factor"),
County = structure(c(1L, 2L, 4L, 3L, NA, NA, NA), .Label = c("Lehigh",
"Mercer", "Montgomery", "Philadelphia"), class = "factor"),
Score = c(3L, 10L, 4L, 8L, 1L, 3L, 6L)), .Names = c("Source",
"County", "Score"), class = "data.frame", row.names = c(NA, -7L
))
在当前文件 NPR、美联社和雅虎新闻没有关联县 (“NA”)。
dput
所需的文件布局:
structure(list(Source = structure(c(5L, 2L, 4L, 3L, 7L, 7L, 7L,
7L, 1L, 1L, 1L, 1L, 6L, 6L, 6L, 6L), .Label = c("Associated Press",
"Daily Ledger", "Herald Tribune", "Inquirer", "Morning Call",
"NPR", "Yahoo News"), class = "factor"), County = structure(c(1L,
2L, 4L, 3L, 1L, 2L, 4L, 3L, 1L, 2L, 4L, 3L, 1L, 2L, 4L, 3L), .Label = c("Lehigh",
"Mercer", "Montgomery", "Philadelphia"), class = "factor"), Score = c(3L,
10L, 4L, 8L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 6L, 6L, 6L, 6L)), .Names = c("Source",
"County", "Score"), class = "data.frame", row.names = c(NA, -16L
))
在所需的布局中,我已将每个国家来源及其分数分配给数据集中的四个县中的每一个。例如,雅虎新闻的 1 分被复制了 4 次,并与 Lehigh、Philadelphia、Montgomery 和 Mercer 县相关联。并且雅虎新闻拥有“NA”县的记录消失了。在我的实际数据集中,我有大约 100 个县,因此雅虎新闻及其相关变量(例如分数、日期、作者等——我总共有大约 60 个变量)将被复制 100 次。我还希望将这些新“重复”记录的县分配给我使用switch
上面的函数创建的 County.Name 变量。我不想要 2 个县名称字段,我想要 County.Names 下的所有这些新创建的县。