I'm looking for what I'm sure is a quick answer. I'm working with a data set that looks like this:
Week Game.ID VTm VPts HTm HPts Differential HomeWin
1 NFL_20050908_OAK@NE OAK 20 NE 30 10 TRUE
1 NFL_20050911_ARI@NYG ARI 19 NYG 42 23 TRUE
1 NFL_20050911_CHI@WAS CHI 7 WAS 9 2 TRUE
1 NFL_20050911_CIN@CLE CIN 27 CLE 13 -14 FALSE
1 NFL_20050911_DAL@SD DAL 28 SD 24 -4 FALSE
1 NFL_20050911_DEN@MIA DEN 10 MIA 34 24 TRUE
NFL data. I want to come up with a way to pair each HTm with its Differential, and store these values in another table. I know it's easy to do, but all the methods I am coming up with involve doing each team individually via a for loop that searches for [i,5]=="NE", [i,5]=="NYG". I'm wondering if there's a way to systematically do this for all 32 teams. I would then use the same method to pair VTM of the same team code ("NYG" or "NE") with VPTs and a VDifferential.
Thanks for the help.
Im not sure if i understood your question correctly(you need a function like select in a database?) but:
cbind(matr[,x], matr[,y])
selects column x and y and creates a new matrix
It sounds like you'd like to perform operations on your data frame based on a grouping variable. For that, there are many functions, among which is tapply()
. For example, if your data is in a data.frame object named nflDF
, you could get the maximum Differential
for each home team HTm
by
tapply(nflDF$Differential, nflDF$HTm, FUN = max)
Which would return (with your sample data)
CLE MIA NE NYG SD WAS
-14 24 10 23 -4 2
Alternatively, you could use by
:
by(nflDF, nflDF$HTm, FUN = function(x) max(x$Differential))
HTm: CLE
[1] -14
------------------------------------------------------------
HTm: MIA
[1] 24
------------------------------------------------------------
HTm: NE
[1] 10
------------------------------------------------------------
HTm: NYG
[1] 23
------------------------------------------------------------
HTm: SD
[1] -4
------------------------------------------------------------
HTm: WAS
[1] 2
To perform more complicated operations, change the values supplied to the FUN
arguments in the appropriate function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.