合并R中的每三列

Combine every three columns in R

我有一个这样的矩阵:

df <- matrix(sample(c(0,1,1),9000,replace=T),nrow=3,ncol=3000)
df[1:3,1:9]

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] 
[1,]    1    0    1    1    1    0    1    1    0   
[2,]    1    1    1    1    1    1    1    1    0   
[3,]    0    0    1    1    0    1    0    1    1   

我想合并每三列以便:

        [,1] [,2] [,3] 
[1,]    101  110  110   
[2,]    111  111  110   
[3,]    001  101  011   

有什么想法吗?? 提前谢谢你

我们可以在循环中使用 seq 来提取每 3 列,然后 pastedata.frame

上使用 do.call 按行提取值
out <- sapply(seq(1, ncol(df), by = 3), function(i)  
       do.call(paste0, as.data.frame(df[, i:(i+2)])))

或者另一种选择是执行一次 paste 然后拆分

v1 <- do.call(paste0, as.data.frame(df))
read.fwf(textConnection(v1), widths = rep(3, nchar(v1[1])/3), 
      colClasses = "character")
#  V1  V2  V3  V4  V5  V6  V7  V8  V9 V10
#1 100 010 111 111 011 011 101 111 111 011
#2 001 101 111 101 101 111 101 111 111 111
#3 110 011 110 001 011 101 111 101 101 111

数据

df <- matrix(sample(c(0, 1, 1), 90, replace = TRUE), nrow = 3,ncol = 30)

假设您有 3 行 30 列的数据集。

df <- matrix(sample(c(0,1,1),9000,replace=T),nrow=3,ncol=30)

每 3 列组合后的总列数。存储到变量 'TotalColumnsAfter'

TotalColumnsAfter <-  ncol(df)/nrow(df)

使用数组函数。转换成数组。

ConvertIntoArray <- array(as.matrix(df), c(nrow(df), TotalColumnsAfter, ncol(df)/TotalColumnsAfter))

使用应用函数合并数组的行和列。 'paste'用于组合。

CombineDataset <- apply(ConvertIntoArray, 1:2, paste, collapse = "") 

这是一个基本的 R 选项,使用 substring 对字符串进行子集化,即

t(
  sapply(
    do.call(paste0, data.frame(df)),
    function(x) substring(x, seq(1, nchar(x), 3), seq(3, nchar(x), 3)),
    USE.NAMES = FALSE
  )
)

这给出了

     [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]
[1,] "101" "101" "110" "011" "110" "011" "111" "111" "010" "010"
[2,] "011" "101" "100" "010" "111" "011" "110" "110" "011" "011"
[3,] "101" "101" "001" "101" "111" "111" "011" "110" "100" "001"

数据

set.seed(0)
df <- matrix(sample(c(0, 1, 1), 90, replace = TRUE), nrow = 3, ncol = 30)

> df
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,]    1    0    1    1    0    1    1    1    0     0     1     1     1     1
[2,]    0    1    1    1    0    1    1    0    0     0     1     0     1     1
[3,]    1    0    1    1    0    1    0    0    1     1     0     1     1     1
     [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26]
[1,]     0     0     1     1     1     1     1     1     1     1     0     1
[2,]     1     0     1     1     1     1     0     1     1     0     0     1
[3,]     1     1     1     1     0     1     1     1     1     0     1     0
     [,27] [,28] [,29] [,30]
[1,]     0     0     1     0
[2,]     1     0     1     1
[3,]     0     0     0     1