-1

I am trying to pad each element of a vector with "0", such that the maximum width is 3

Example:

  • 0 becomes 000
  • 12 becomes 012
  • 100 stays 100

Here is the code

myvector <- c("2", "3", "33", "90", "120")
newvector <- lapply(myvector,formatC(width=3, format="s", flag="0"))

And when I use lapply, I get error

Error in formatC(width = 3, format = "s", flag = "0") : 
  argument "x" is missing, with no default

Which makes no sense because I am using it in lapply, and the first argument of lapply is myvector.

josliber
  • 43,891
  • 12
  • 98
  • 133
Rhonda
  • 1,661
  • 5
  • 31
  • 65
  • Is this for the Coursera R Programming course? If so, or for future searchers who end up here: instead of padding, try `list.files()` and then `lapply()` with `read.csv()` to just read _all_ of the files in that directory. There are many approaches to parts of this assignment on SO. – Sam Firke Jul 20 '15 at 17:29
  • @SamFirke Yes, coursera ... how did you guess??? I was just researching general idea instead of using actual question.... Eventually I need to append the file extension before doing the `read.csv()` Thanks for the pointers though .... – Rhonda Jul 20 '15 at 17:39

1 Answers1

3

You need to pass each element of the vector to formatC (and you'll also want to pass them as numbers to get the 0 padding):

myvector <- c("2", "3", "33", "90", "120")
newvector <- lapply(myvector, function(x) formatC(as.numeric(x), width=3, flag="0"))
newvector
# [[1]]
# [1] "002"
# 
# [[2]]
# [1] "003"
# 
# [[3]]
# [1] "033"
# 
# [[4]]
# [1] "090"
# 
# [[5]]
# [1] "120"

If you wanted a vector instead of a list, you could use sapply instead of lapply.

josliber
  • 43,891
  • 12
  • 98
  • 133
  • This works, but please explain why. When I go to sapply help pages, it gives the format of `sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)`; where does `function(x)` fit into this? I understand `as.numeric(x)` will be the output. Please clarify. – Rhonda Jul 20 '15 at 17:33
  • Nice, I never thought to use `formatC` for this problem, I always do something like `substr(paste0("000",x),nchar(x)-2,nchar(x)`. I imagine this is exactly what `formatC` does, but faster. – MichaelChirico Jul 20 '15 at 17:44
  • @SohniMahiwal the `FUN` argument needs to be passed a function, so we pass it `function(x) formatC(as.numeric(x), width=3, flag="0")`, which is a function that takes an argument called `x` and calls `formatC` on it. Just by running `formatC("2", width=3, flag="0")` and `formatC(2, width=3, flag="0")` you should be able to figure out why we need to convert "2" into 2. – josliber Jul 20 '15 at 17:55
  • @josilber Ah, ok, so each element of myvector is passed into `function(x)` ... and I understand the `as.numeric(x)` – Rhonda Jul 20 '15 at 18:02