I have a huge data frame df, with in one column a 'year-month' value as follows: "YYYYMM". Currently the data type is a number. Snapshot:
> df[[1]][1:10]
[1] 201001 201001 201001 201001 201001 201001 201001 201001 201001 201001
> str(df)
'data.frame': 2982393 obs. of 11 variables:
$ YearMonth : int 201001 201001 201001 201001 201001 201001 201001 201001 201001 201001 ...
$ ...
What I want is to transform this value to a string (eventually to a factor) in the form "YYYY-MM", to be able to compare this with other data frames.
I'm struggling to find an easy way to transform the value.
I tried using as.Date and the format function. But as the values do not have any days, it didn't work for Strings. With Numerics (same with dataframe column) I even got other problems.
> as.Date("201001", format = "%Y%m")
[1] NA
> as.Date(201001, format = "%Y%m")
Error in as.Date.numeric(201001, format = "%Y%m") :
'origin' must be supplied
> as.Date(df[[1]], format = "%Y%m")
Error in as.Date.numeric(df[[1]], format = "%Y%m") :
'origin' must be supplied
I'm able to transform just one value, using subset and concatenation of strings.
I wrote the formula below, to handle one element:
transformString <- function( x ) { # x = value
return ( paste(cbind(substring(x, 1, 4),"-",substring(x,5,6)), collapse = '') )
}
Problem: I didn't find an easy way to apply that function to a whole column of an data.frame, other than just traversing all elements:
transformStringVector <- function( x ) { # x = vector
for(i in 1:length(x)) {
x[i]<-transformString(x[i])
}
return ( x )
}
This is far from elegant and bad for performance. I tried to use apply (see below) and stuff like that, but was confronted with errors... (I admit I do not really get the apply function)
> temp <- apply(df[[1]], 1, transformString )
Error in apply(df[[1]], 1, transformString ) :
dim(X) must have a positive length
Does anybody have an alternative for this transformation within a huge data.frame? Or more in general; an easy way to apply string-like-transformations to elements within a data.frame?