【发布时间】:2014-09-11 02:55:36
【问题描述】:
我正在尝试使用 ddply 规范化数据(由变量“季节”子集),但它在我正在规范化的数据(第 4 列)的前面插入季节变量,然后将所有数据转移到正确的。
我是 dplyr/plyr 世界的新手,因此不胜感激。
完全可重现的例子:
library(plyr)
library(dplyr)
library(XML)
library(stringr)
# File Names, Functions, Parameters, etc.
# custom functions
normalize <- function(x) {
return((x - min(x)) / (max(x) - min(x)))
}
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
first_season <- 2004
last_season <- 2013
num_seasons <- as.numeric(last_season - first_season + 1)
seasons <- seq(first_season, last_season, by=1)
rm(first_season, last_season)
# Passing
passing <- data.frame()
for (i in 1:num_seasons) {
url <- paste("http://www.pro-football-reference.com/years/", seasons[i],"/passing.htm", sep = "")
df <- readHTMLTable(url,which=1)
df$season = seasons[i]
df <- df[!names(df) %in% c("QBrec") ]
if(df$season >= 2008) df <- df[!names(df) %in% c("QBR") ] # Removes QBR 2008+
passing <- rbind(passing, df)
rm(df)
print(seasons[i])
}
names(passing) <- c("rank_pfr", "nameinfo", "team", "age", "games", "games_started",
#"qb_record",
"completions", "attempts", "comp_pct", "yards_passing",
"td_passing", "td_pct", "interceptions", "int_pct", "long_passing",
"yards_pass_att", "yards_pass_att_avg", "yards_pass_comp", "yards_pass_game", "pass_rate", "sacks", "sacks_pass", "yards_net_pass_att", "yards_net_pass_att_avg", "sacks_pct", "comebacks", "game_win_drives", "season")
passing <- passing[which(passing$rank_pfr!='Rk'), ]
passing[, 4:28] <- apply(passing[,4:28], 2, as.numeric)
passing[is.na(passing)] <- 0
# Note that season is the last column (both colname and viewing the data)
# colnames(passing)
# View(passing)
passing[, 4:28] <- plyr::ddply(passing[, 4:28], .(season), colwise(normalize))
# Note that season still *appears* to be the last column
# colnames(passing)
# But when you view the data the season values have been
# inserted under age, and everything else seems to be shifted to the right
# View(passing)
谢谢!
【问题讨论】:
-
如果您可以将最小的工作示例限制为仅发生意外重新排序的那些代码行并将输入数据提供为
dput,这将更容易。 -
@beginneR 因为我要从多个站点抓取数据,所以我不知道如何真正将其最小化。另外,我过去曾因没有足够的代码而受到批评。
-
好的,我明白了。只是以为您可能会得到更快的响应。您描述的重新排序发生在最后一次
ddply调用中是否正确? -
@beginneR 我对 SO 有点陌生,所以我也很欣赏礼仪建议。
-
@beginneR 重新排序的代码是
passing[, 4:28] <- plyr::ddply(passing[, 4:28], .(season), colwise(normalize))
标签: r normalization plyr