I would like to split a string at regular intervals. My question is virtually identical to this one: How to split a string into substrings of a given length? except that I have a column of strings in a data set instead of just one string.
Here is an example data set:
df = read.table(text = "
my.id X1
010101 1
010102 1
010103 1
010104 1
020101 1
020112 1
021701 0
021802 0
133301 0
133302 0
241114 0
241215 0
", header = TRUE, colClasses=c('character', 'numeric'), stringsAsFactors = FALSE)
Here is the desired result. I would prefer to remove the leading zeroes, as shown:
desired.result = read.table(text = "
A1 A2 A3 X1
1 1 1 1
1 1 2 1
1 1 3 1
1 1 4 1
2 1 1 1
2 1 12 1
2 17 1 0
2 18 2 0
13 33 1 0
13 33 2 0
24 11 14 0
24 12 15 0
", header = TRUE, colClasses=c('numeric', 'numeric', 'numeric', 'numeric'), stringsAsFactors = FALSE)
Here is a loop that seems to come close and maybe I can use it. However, I am thinking that there is likely a more efficient way.
for(i in 1:nrow(df)) {
print(substring(df$my.id[i], seq(1, 5, 2), seq(2, 6, 2)))
}
This apply
statement does not work:
apply(df$my.id, 1, function(x) substring(df$my.id[x], seq(1, 5, 2), seq(2, 6, 2)) )
Thank you for any suggestions. I prefer a solution in base R.