Home > Back-end >  loop slicing in R and rbind them
loop slicing in R and rbind them

Time:09-26

I have a dataset with 2 rows and 280 columns. I want to slice every 8 columns and after that, I want to rbind them. I am showing an example:

dat1 <- df[c(1:9)]
dat2 <- df[c(10:18)]
df = rbind(dat1,dat2)

I want to do this for 280 columns in the loop in R. After every 8 columns, the columns are repetitive in 280 columns. After 8 columns they are the same, that's why I want to rbind them. I am very new to coding. Appreciate any kind of help.

enter image description here

enter image description here

CodePudding user response:

You can use split() and rbind() with do.call():

bnames = colnames(df)[1:8]
do.call(
  rbind,
  lapply(split.default(df,rep(1:(280/8),each=8)),setNames, nm=bnames)
)

CodePudding user response:

You can do this by recycling a logical vector. For example, the code below with drop every 8th column.

subset(df, select = c(rep(TRUE, 7), FALSE))

Now that I understand a little better, you could do something like this. You just loop through the columns and subset by groups of 8. It isn't very elegant though. I personally don't love loops, so I'm thinking about an alternative.

final <- data.frame()
for(i in 1:(280/8)){
  test <- df[,{(i*8-8) 1}:{i*8}]
  final <- rbind(final, test)
}

EDIT:

Here is another method. It looks a little more confusing at first glance, but it should be pretty flexible (assuming your column names really repeat every 8 columns). First, we map out the first column index, then we subset the columns based on the first index and the last index (first 7). I added .x:min(c(.x 7, ncol(df))) so that is stops at the last column if your dataset isn't perfectly divisible by 8.

library(tidyverse)

map(seq(1, ncol(df), by = 8),
    ~df %>%
      select(all_of(.x:min(c(.x 7, ncol(df)))))) |>
  bind_rows()
  • Related