粘贴两列的元素 [英] Paste the elements of two columns

查看:40
本文介绍了粘贴两列的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的 data.frame

I have a data.frame of the 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
#   a 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 would like to take the first two columns, convert the integer into characters and paste the two elements of the same row together. Then repeat the process each successive pair of columns.

这是一个可以正确完成工作的脚本:

Here is a script that would do the 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))
    for (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"

但是我的 data.frame 实际上非常大并且在 R 中循环遍历整个 data.frame 非常慢.你有更有效的解决方案吗?Rcpp 可能是解决方案,但我不知道如何用 C++ 编码.

But my data.frame is actually very big and looping through the whole data.frame in R is very slow. Do you have a more efficient solution? Rcpp might be the solution but I don't know how to code in C++.

推荐答案

这与您的描述相符,但与您显示的输出不相符:

This matches your description, but not the output you show:

mat = as.matrix(d)

matrix(paste0(mat[, seq(1, ncol(mat), by = 2)],
              mat[, seq(2, ncol(mat), by = 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"

当然,您可以将结果转换为数字、返回到 data.frame 等.

You could, of course, convert the result to numeric, back to a data.frame, etc.

这篇关于粘贴两列的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆