1

I have a dataframe with the following structure:

V1 V2 V3 V4 V5 V6 V7 V8
A B A B B A B B

It's only one row and each column has one letter. I wanna take these letters, two by two and insert them in another dataframe, as follows:

V1 V2 V3
X AB F
Y AB G
Z BA H
W BB I

How should I proceed? Maybe turn the first dataframe into a vector?

Thanks in advance!

1
  • How do you get V1 and V3 ? Commented Sep 11, 2020 at 14:32

3 Answers 3

1

I have no clue where V1 and V3 come from, but the code below can help you produce V2

do.call(rbind,
  Map(function(x) do.call(paste0,x),
  split.default(df1,ceiling(seq_along(df1)/2)))
)

which gives

  [,1]
1 "AB"
2 "AB"
3 "BA"
4 "BB"

Data

> dput(df1)
structure(list(V1 = "A", V2 = "B", V3 = "A", V4 = "B", V5 = "B", 
    V6 = "A", V7 = "B", V8 = "B"), class = "data.frame", row.names = c(NA,
-1L))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, it worked! V1 and V3 were just intended to show there are other columns in the dataframe. I'm sorry about the confusion, I'm not used to ask questions here.
1

Here is a more long-winded way of doing this.

xy <- structure(list(V1 = "A", V2 = "B", V3 = "A", V4 = "B", V5 = "B", 
               V6 = "A", V7 = "B", V8 = "B"), class = "data.frame", row.names = c(NA,
                                                                                  -1L))
xy <- unlist(xy)  # split doesn't work on data.frames

# Make sure that length of xy is divisible by 2.
stopifnot((length(xy) %% 2) == 0)

tosplit <- rep(1:(length(xy) / 2), each = 2)
tosplit <- factor(tosplit)

xy <- split(xy, f = tosplit)
xy <- lapply(xy, FUN = paste, collapse = "")
xy <- unlist(xy)
xy

   1    2    3    4 
"AB" "AB" "BA" "BB" 

This can easily be manipulated into a data.frame of your choosing.

Comments

0

We can also convert to a matrix of two columns and then do the paste

do.call(paste0, as.data.frame(matrix(unlist(df1), ncol = 2, byrow = TRUE)))
#[1] "AB" "AB" "BA" "BB"

data

df1 <- structure(list(V1 = "A", V2 = "B", V3 = "A", V4 = "B", V5 = "B", 
    V6 = "A", V7 = "B", V8 = "B"), class = "data.frame", row.names = c(NA,
-1L))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.