I am a very new R user and have a problem with mutating a new variable for the dataset below. I would like to create a new numeric column and assign value 1 if company!=NA, while assign value 2 if company==NA. Then, I would like to assign the label "Yes" to 1s and "No" otherwise.
Thanks,
MRR
fy <- c(2010,2011,2012,2010,2011,2012,2010,2011,2012)
company <- c(NA,NA,"Apple","Google","Google","Google","Microsoft","Microsoft","Microsoft")
revenue <- c(65225,108249,156508,29321,37905,50175,62484,69943,73723)
profit <- c(14013,25922,41733,8505,9737,10737,18760,23150,16978)
companiesData <- data.frame(fy, company, revenue, profit)
CodePudding user response:
fy <- c(2010,2011,2012,2010,2011,2012,2010,2011,2012)
company <- c(NA,NA,"Apple","Google","Google","Google","Microsoft","Microsoft","Microsoft")
revenue <- c(65225,108249,156508,29321,37905,50175,62484,69943,73723)
profit <- c(14013,25922,41733,8505,9737,10737,18760,23150,16978)
companiesData <- data.frame(fy, company, revenue, profit)
companiesData <- companiesData %>%
mutate(column1 = ifelse(!is.na(company), 1, 0),
column2 = ifelse(!is.na(company), "Yes", "No"))
CodePudding user response:
We may use base R
companiesData$column1 <- with(companiesData, c("No", "Yes")[1 !is.na(company)])