r - Paste the elements of two columns -
this question has answer here:
i have data.frame of following kind
set.seed(12) d = data.frame(a=sample(5,x=1:9), b=sample(5,x=1:9), c=sample(5,x=1:9), d=sample(5,x=1:9), e=sample(5,x=1:9), f=sample(5,x=1:9)) d # b c d e f # 1 1 1 4 4 2 3 # 2 7 2 7 9 7 5 # 3 8 5 3 8 1 2 # 4 2 9 8 7 5 9 # 5 9 6 2 1 9 4
i take first 2 columns, convert integer characters , paste 2 elements of same row together. repeat process each successive pair of columns.
here script job correctly:
bar = function (twocols) {sapply(1:nrow(twocols), fun=function(x) {paste(twocols[x,], collapse="")} )} count = 0 out = matrix(0, ncol=ncol(d)/2, nrow=nrow(d)) (i in seq(1,ncol(d), 2)) { count = count+1 out[,count] = bar(d[,i:(i+1)]) } print(out) [,1] [,2] [,3] [1,] "11" "44" "23" [2,] "72" "79" "75" [3,] "85" "38" "12" [4,] "29" "87" "59" [5,] "96" "21" "94"
but data.frame big , looping through whole data.frame in r slow. have more efficient solution? rcpp
might solution don't know how code in c++.
this matches description, not output show:
mat = as.matrix(d) matrix(paste0(mat[, seq(1, ncol(mat), = 2)], mat[, seq(2, ncol(mat), = 2)]), ncol = ncol(mat) / 2) # [,1] [,2] [,3] # [1,] "11" "44" "23" # [2,] "72" "79" "75" # [3,] "85" "38" "12" # [4,] "29" "87" "59" # [5,] "96" "21" "94"
you could, of course, convert result numeric, data.frame, etc.
Comments
Post a Comment