简体   繁体   中英

Is there an R function for taking the first four characters in a column and putting them into a new column?

I have different/non-repeating years at the beginning of a column (Details) in my data frame (Data) that I would like to split off and create a "Years" Column with. Based on other questions that have been answered, I am assuming I would use tstrsplit. However, I don't understand how to actually use the function to get it to do what I want.

When you want characters from a fixed position within the string (like the first 4 characters) substr is quick and easy.

Data$Years = substr(Data$Details, 1, 4)

strsplit needs something to split at, so if you had "2020-04-02" you could split at "-" characters. But if you know you want the first four, substr is best.

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