Using DF
defined in the Note at the end create a sprintf
formatting string fmt
and then run it.
If there are NA's in DF
then they will appear in the output as the string "NA"
. If you prefer to omit them completely then replace them with the empty string in DF
before running the code below, i.e. run DF[is.na(DF)] <- ""
first.
fmt <- paste(rep(strrep("%s", 5), ncol(DF)/5), collapse = "-") # %s%s%s%s%s-%s%s%s%s%s
Output <- do.call("sprintf", c(fmt, DF))
data.frame(DF, Output, stringsAsFactors = FALSE)
giving:
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 Output
1 044 N 005 E 026 044 N 006 E 011 044N005E026-044N006E011
or using DF2
from Note in place of DF
we get:
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 Output
1 044 N 005 E 026 044 N 006 E 011 044N005E026-044N006E011
2 045 S 006 F 027 045 S 007 F 012 045S006F027-045S007F012
data.table
If, as per comment, you want to use data.table then use this (with fmt
from above):
library(data.table)
DT <- data.table(DF)
DT[, Output:=do.call("sprintf", c(fmt, .SD))]
Note
Lines <- "
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38
044 N 005 E 026 044 N 006 E 011 "
DF <- read.table(text = Lines, header = TRUE, colClasses = "character")
Lines2 <- "
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38
1 044 N 005 E 026 044 N 006 E 011
2 045 S 006 F 027 045 S 007 F 012"
DF2 <- read.table(text = Lines2, header = TRUE, colClasses = "character")