There are multiple ways that you can do it. But to keep things simple I'll show the traditional for
loop approach with base R, the mapply
approach with base R, and share the tidyverse
approach also.
Base R Approach - Using for
loops
library(wooldridge)
data(wage2)
# Traditional solution
# Make new variable
wage2$tenure_new<- NA
for(i in 1:length(wage2$tenure)){
if(wage2$tenure[i]<= wage2$exper[i]){
wage2$tenure_new[i]<- wage2$tenure[i]
}else{
wage2$tenure_new[i]<- wage2$exper[i]
}
}
# mean of tenure_new
round(mean(wage2$tenure_new),2)
# Output> [1] 6.51
Base R Approach- using mapply
A really small amount of code, but hard to read if you don't know R well.
round(mean(mapply(function(x,y) if(x<=y){x}else{y},x=wage2$tenure,y=wage2$exper)),2)
tidyverse
Approach
(Actually you can use dplyr
package alone but I personally like to load tidyverse
in its entirety.)
library(tidyverse)
wage2 %>%
transmute(tenure_new=ifelse(tenure<=exper,tenure,exper)) %>%
colMeans() %>%
round(2)
# Output> tenure_new
# 6.51