Alana
Alana

Reputation: 185

Creating a column in a dataframe with values from another dataframe in R

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!

Upvotes: 1

Views: 78

Answers (3)

akrun
akrun

Reputation: 887118

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))

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70643

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.

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101373

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))

Upvotes: 1

Related Questions