R collapsing columns and formatting -
this question has answer here:
- paste column values column 2 answers
suppose have data.frame looks this
1 5 9 12 34 38 10 40
how collapse columns, place separator in between, , add instance character "a" beginning , "b" end get:
a1&5b a9&12b a34&38b a10&40b
thank you,
use paste
or sprintf
. see ?paste
, ?sprintf
.
when "a list", mean each element of list string 2 numbers (e.g. x[[1]] = "1 5"
), or mean have numeric matrix (e.g. x[1, ] = c(1, 5)
) or .. ?
# e.g. if x dataframe x <- data.frame(a=c(1, 9, 34, 10), b=c(5, 12, 38, 40)) sprintf('a%i&%ib', x$a, x$b) # or paste0("a", x$a, "&", x$b, "b") # paste0 has no separator; paste has " " separator
or supposing had many columns (not , b) , didn't want type them out manually, put '&' between each value in row, paste "a" on front , "b" on back.
paste0("a", apply(x, 1, paste, collapse='&'), "b")
essentially goes along each row (e.g. row 1 c(1, 5)
), collapse contents '&' in between (paste(c(1,5), collapse="&"
), , paste , b on either side of result (paste0
shorthand paste(..., sep="")
).
Comments
Post a Comment