0

So I have a relatively simple problem (and I think that there may be some duplicates of my question out there) but I just can't seem to figure it out and I would really appreciate any and all help.

I have a dataset and in one column, I have multiple rows of different 11-digit numbers. I hope to obtain the last 6 digits of each number and I hope to be able to create a new column in my dataset with the results.

Below is an example:

random_num <- c(11001100100, 11001100300, 11001100400,
                11001100501, 11001100502, 11001100600)
random_stuff <- c(2, 5, 6, 2, 5, 3)
data_frame <- cbind(random_num, random_stuff)

And I hope to get an output that shows something like this:

endresult

So far, this is what I have:

conversion <- function (x) {
  for (i in nrow(x)) 
  {
  c <- as.character[i]
  be <- substring(c, seq(1, nchar(c), 1), seq(1, nchar(c), 1))
  ad <- paste(be[6], be[7], be[8], be[9], be[10], be[11], sep = "")
  final <- as.numeric(ad)
  return(final)
  }
}

finalr <- conversion(data_frame)
finalr

But I either get the error message saying that

'Error in as.character[i]: object of type 'builtin' is not subsettable' or 'Error in mutate_impl(.data, dots) : Evaluation error: 'to' must be of length 1.'

Will really appreciate any advice. Thank you!

DGOH
  • 25
  • 4

2 Answers2

1

From what I can, the result column/vector is just the last six digits from the random_num vector. So, we can use the modulus to compute this:

random_num <- c(1100100100, 1100100300, 1100100400,
                1100100501, 1100100502, 1100100600)
result <- random_num %% 1000000
result

[1] 100100 100300 100400 100501 100502 100600

This answer avoids a potentially unnecessary cast from numeric to character.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

I've converted your dataset in a dataframe:

random_num <- c(11001100100, 11001100300, 11001100400,
                11001100501, 11001100502, 11001100600)
random_stuff <- c(2, 5, 6, 2, 5, 3)
data_frame <- data.frame(random_num, random_stuff)

data_frame$result <- substring(data_frame$random_num, nchar(data_frame$random_num)-6+1)


> data_frame
   random_num random_stuff result
1 11001100100            2 100100
2 11001100300            5 100300
3 11001100400            6 100400
4 11001100501            2 100501
5 11001100502            5 100502
6 11001100600            3 100600
Stewart Macdonald
  • 2,062
  • 24
  • 27