简体   繁体   中英

How do you convert year values in a dataframe into 2-digit values?

I have tried using this formula to convert the year mentioned in my dataframe "Yr" into a 2-digit value

yr <- format((Yr[,]), format = "%y")

note: Yr is a data.frame which consists of year values viz. 2015, 2012, 1998 etc. I am trying to load these values into the variable yr in the following format 15, 12, 98 respectively.

How about sprintf("%02d", Year %% 100) ?

Year <- 1960:2016
sprintf("%02d", Year %% 100)
# [1] "60" "61" "62" "63" "64" "65" "66" "67" "68" "69" "70" "71" "72" "73" "74"
#[16] "75" "76" "77" "78" "79" "80" "81" "82" "83" "84" "85" "86" "87" "88" "89"
#[31] "90" "91" "92" "93" "94" "95" "96" "97" "98" "99" "00" "01" "02" "03" "04"
#[46] "05" "06" "07" "08" "09" "10" "11" "12" "13" "14" "15" "16"

Another way is to use substr , as commented by @alistaire:

substr(Year, 3, 4)
# [1] "60" "61" "62" "63" "64" "65" "66" "67" "68" "69" "70" "71" "72" "73" "74"
#[16] "75" "76" "77" "78" "79" "80" "81" "82" "83" "84" "85" "86" "87" "88" "89"
#[31] "90" "91" "92" "93" "94" "95" "96" "97" "98" "99" "00" "01" "02" "03" "04"
#[46] "05" "06" "07" "08" "09" "10" "11" "12" "13" "14" "15" "16"

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