split one long row into columns

Hi, I have a following problem: My data are in one long row, like this:

df <- data.frame(c("A"), c("B"), c("C"), c("1"), c("2"), c("3"))

I would like to to break the row on every third place and create a dataframe n x 3, like this:

newdf <- newdf <- data.frame(c("A","1"), c("B","2"), c("C","3"))

How can I do this, please?

before I look at this further, can you confirm if the following represents your starting and desired end point ?



data.frame(h1=c("A"),
           h2=c("B"),
           h3=c("C"),
           v1=c("1"),
           v2=c("2"),
           v3=c("3"),
           v4=c("4"),
           v5=c("5"),
           v6=c("6"))


data.frame(A=c("1","4"),
           B=c("2","5"),
           C=c("3","6"))

Yes, exactly, that is what I need!

no error checking in my solution, so splitnum needs to be accurate for the job.

original_df <- data.frame(
           h1=c("A"),
           h2=c("B"),
           h3=c("C"),
           v1=c("1"),
           v2=c("2"),
           v3=c("3"),
           v4=c("4"),
           v5=c("5"),
           v6=c("6"))
> original_df
  h1 h2 h3 v1 v2 v3 v4 v5 v6
1  A  B  C  1  2  3  4  5  6

redim <- function(start_df, splitnum)
{
as_vec <- as.character(t(start_df))
vec_len <- length(as_vec)

indexlist <- list()
for (i in 1:splitnum)
{
  indexlist[[i]] <- seq.int(from = splitnum+i,
                            by = splitnum,
                            to = vec_len)
}


vectorlist <- list()
for (i in 1:splitnum)
{
  vectorlist[[i]] <-  as_vec[indexlist[[i]]]
}

new_df <- bind_cols(vectorlist)
# new_df <- bind_cols(v1=v1,v2=v2,v3=v3)

header <- as_vec[1:splitnum]
names(new_df) <- header
new_df
}

> redim(original_df,3)
# A tibble: 2 x 3
  A     B     C    
  <chr> <chr> <chr>
1 1     2     3    
2 4     5     6
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.