0

I have a table called "new" and I wanted to extract year from ManufactureDate to a new column "year".

new$ManufactureDate:

2014-01-01 
2016-01-01
2005-01-01
1997-11-01

Create a new column and "new" will look like this:

ManufactureDate    year
2014-01-01         2014
2016-01-01         2016
2005-01-01         2005
1997-11-01         1997

My code:

for (i in 1:nrow(new)){
  new["year"] <- NA
  new$year[i] <- strsplit(new$ManufactureDate, "-")[[i]][1]
  print(new$year[i])
}

Result: It printed out successfully, but when I checked table "new", it shows like this, not sure what happened:

ManufactureDate    year
2014-01-01         NA
2016-01-01         NA
2005-01-01         NA
1997-11-01         1997
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Lara19
  • 615
  • 1
  • 9
  • 20

2 Answers2

1

There's no need for a for loop. Along with what you've tried so far (using strsplit), here is one possibility:

new$year <- sapply(strsplit(as.character(new$ManufactureDate), "-"), "[[", 1);
#  ManufactureDate year
#1      2014-01-01 2014
#2      2016-01-01 2016
#3      2005-01-01 2005
#4      1997-11-01 1997

Sample data

new <- read.table(text =
    "ManufactureDate
    2014-01-01
2016-01-01
2005-01-01
1997-11-01", header = T)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • Thanks! It works well! I just haven't learned how to use sapply yet. – Lara19 Feb 23 '18 at 02:16
  • No worries @Lara19; familiarising yourself with `sapply`/`lapply` (and the whole `*apply` family) will definitely be time well spent for future R coding. – Maurits Evers Feb 23 '18 at 02:20
1

I'm actually going to vote against even creating the year column. If you are using an actual date column, then you should extract the year from that already existing column, rather than denormalizing your data and creating a dummy year column.

df <- data.frame(ManufactureDate=as.Date(c("2014-01-01", "2016-01-01",
                                           "2005-01-01", "1997-11-01")))
format(df$ManufactureDate, "%Y")
[1] "2014" "2016" "2005" "1997"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360