简体   繁体   中英

Creating a new column with an if function in R

I am currently dealing with data on NFL Teams. Basically what I am trying to do here is create a new column titled Conference . I am trying to create an if function that generates the conference based off the Team in the Team column. My data set is called NFL_DATA and the column i am interested in is Team so I am using NFL_DATA$Team . Basically I am trying to say if NFL_DATA$TEAM == 'Philadelphia Eagles' or 'Dallas Cowboys' or 'New York Giants' or 'Washington Redskins' Then it will equal NFC East. Then in the conference column NFC East will appear for any of these teams. I am trying to do this for all 8 conferences. Any help would be greatly appreciated!!

So Far this is what I have and Im sure this is off:

Conference <- function(NFL_DATA$Team) {
  if (NFL_DATA$Team == 'Phiadelphia Eagles' | 'Dallas Cowboys' | 'New York Giants' | 'Washington Redskins') y <- "NFC EAST"
}

No need for a function here:

east <- c('Phiadelphia Eagles', 'Dallas Cowboys', 'New York Giants', 'Washington Redskins')

transform(NFL_DATA, Conference = ifelse(Team %in% east, "NFC EAST", "something else")

Dplyr's case_when is handy for long ifelse statments:

library(dplyr)
NFL_Data <-
  NFL_Data %>% mutate("Conference" = case_when(
    Team %in% c(
      'Phiadelphia Eagles' ,
      'Dallas Cowboys' ,
      'New York Giants' ,
      'Washington Redskins'
    ) ~ 'NFC EAST',
    Team %in% c(
      'New England Patriots' ,
      'Buffalo Bills' ,
      'New York Jets' ,
      'Miami Dolphins'
    ) ~ 'AFC EAST',
    TRUE ~ "NFC WEST"
  )

You can keep adding Team %in% c("List_of_Teams") ~ "Conference_Name" lines before the TRUE ~ "NFC WEST" for the remaining NFL conferences.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM