Merge columns into a single string in R

Asked

Viewed 45 times

1

Suppose the following date.frame:

df<-data.frame(V1 = c(9,1,4,2,3,0,7,9,5),
       V2 = c(9,2,5,4,7,9,2,3,8),
       V3 = c(9,8,5,7,4,0,2,9,3),
       V4 = c(9,7,3,6,2,9,5,8,4),
       V5 = c(9,2,5,4,0,3,9,4,8))

  V1 V2 V3 V4 V5
1  9  9  9  9  9
2  1  2  8  7  2
3  4  5  5  3  5
4  2  4  7  6  4
5  3  7  4  2  0
6  0  9  0  9  3
7  7  2  2  5  9
8  9  3  9  8  4
9  5  8  3  4  8

I would like to create a 6th column with the numbers all together.

I’m using the function paste(), but it’s not going as expected.

df %>% 
  mutate(junto = paste0(df[,1],df[,5]))


  V1 V2 V3 V4 V5 junto
1  9  9  9  9  9    99
2  1  2  8  7  2    12
3  4  5  5  3  5    45
4  2  4  7  6  4    24
5  3  7  4  2  0    30
6  0  9  0  9  3    03
7  7  2  2  5  9    79
8  9  3  9  8  4    94
9  5  8  3  4  8    58
> 

Function glues the columns "V1" and "V5".

But actually, I’d like you to glue from 'V1' until 'V5'.

I tried to use the "two dots" df[,1]:df[,5], but it didn’t work either

df %>% 
  mutate(junto = paste0(df[,1]:df[,5]))

  V1 V2 V3 V4 V5 junto
1  9  9  9  9  9     9
2  1  2  8  7  2     9
3  4  5  5  3  5     9
4  2  4  7  6  4     9
5  3  7  4  2  0     9
6  0  9  0  9  3     9
7  7  2  2  5  9     9
8  9  3  9  8  4     9
9  5  8  3  4  8     9

Warning messages:
1: In df[, 1]:df[, 5] :
  numerical expression has 9 elements: only the first used
2: In df[, 1]:df[, 5] :
  numerical expression has 9 elements: only the first used

I took a look at that reply, but still I’m not getting it

1 answer

6


Can use apply to apply paste to the selected lines (using collapse instead of sep):

df$junto <- apply(df[, 1:5], 1, paste, collapse = "")

> head(df)
  V1 V2 V3 V4 V5 junto
1  9  9  9  9  9 99999
2  1  2  8  7  2 12872
3  4  5  5  3  5 45535
4  2  4  7  6  4 24764
5  3  7  4  2  0 37420
6  0  9  0  9  3 09093

Browser other questions tagged

You are not signed in. Login or sign up in order to post.