kezz123
kezz123

Reputation: 1

Pasting one column to every other column in a dataframe

I have a bunch of columns and I need to paste the first column into every other column. It looks like this except actual words instead of letters, and theres a few hundred columns.

           TEST0     TEST1     TEST2     TEST3     TEST4
       1   Q1:       AA AA AA  AA AA AA            BB BB BB
       2   Q2:                                        
       3   Q3:       BB BB BB  CC CC CC  CC CC CC  CC CC CC 
       4   Q4:       DD DD DD            DD DD DD  DD DD DD

I'm able to paste the first column into another column one at a time doing this:

    paste(test[,2],test[,3])
   [1] "Q1: AA AA AA"  "Q2: "          "Q3: BB BB BB"  "Q4: DD DD DD "

    paste(test[,2],test[,4])
   [1] "Q1: AA AA AA " "Q2: "          "Q3: CC CC CC " "Q4: "    

but is there a way to do multiple columns at once? Thanks

Upvotes: 0

Views: 223

Answers (3)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

{dplyr} is surprisingly convoluted for this case. A much easier solution is to use lapply (which works since data.frames are lists of columns):

as.data.frame(lapply(test[-1], function (x) paste(test[[1]], x)))

Upvotes: 0

Jordi
Jordi

Reputation: 1343

This is a base solution with a for loop. For every target column, paste the
first column to it.

df <- data.frame(a = letters[1:5], b = 1:5, c = 5:1)

for (i in 2:length(df)) {
    df[[i]] <- paste(df[[1]], df[[i]], sep = ": ")
}

Where length gives the number of columns of a data.frame.

Result:

  a    b    c
1 a a: 1 a: 5
2 b b: 2 b: 4
3 c c: 3 c: 3
4 d d: 4 d: 2
5 e e: 5 e: 1

Upvotes: 0

Martin Schmelzer
Martin Schmelzer

Reputation: 23889

Here is a way of doing it with dplyr. Create your own pasting function first:

df <- data.frame(A = LETTERS, B = 1:26, C = 1:26)
head(df)

   A  B  C
1  A  1  1
2  B  2  2
3  C  3  3
4  D  4  4
5  E  5  5

pasteA <- function(., x) paste0(df$A,.)
df %>%
  mutate_if(.predicate = c(F, rep(T, ncol(df)-1)), .funs = list(pasteA))

   A   B   C
1  A  A1  A1
2  B  B2  B2
3  C  C3  C3
4  D  D4  D4
5  E  E5  E5

We use mutate_if to select all columns except the first one using a logical vector.

Upvotes: 1

Related Questions