How to concatenate column values and create a new column in an R data frame?



Sometimes we want to combine column values of two columns to create a new column. This is mostly used when we have a unique column that maybe combined with a numerical or any other type of column. Also, we can do this by separating the column values that is going to be created with difference characters. And it can be done with the help of apply function.

Example

Consider the below data frame −

 Live Demo

> ID<-1:20 > Country<- sample(c("Russia","USA","China","Canada","UK","India","Nepal"),20,replace=TRUE) > df1<-data.frame(ID,Country) > df1

Output

 ID Country 1 1 UK 2 2 UK 3 3 India 4 4 USA 5 5 USA 6 6 UK 7 7 Nepal 8 8 Russia 9 9 Nepal 10 10 China 11 11 UK 12 12 Nepal 13 13 Canada 14 14 USA 15 15 Russia 16 16 UK 17 17 China 18 18 USA 19 19 China 20 20 Russia

Creating a new column of ID and Country −

> df1$ID_with_Country<-apply(df1,1,paste,collapse="") > df1

Output

 ID Country ID_with_Country 1 1    UK       1UK 2 2    UK       2UK 3 3   India    3India 4 4    USA     4USA 5 5   USA       5USA 6 6    UK       6UK 7 7    Nepal  7Nepal 8 8   Russia  8Russia 9 9   Nepal    9Nepal 10 10 China    10China 11 11  UK       11UK 12 12 Nepal    12Nepal 13 13 Canada 13Canada 14 14  USA    14USA 15 15 Russia    15Russia 16 16  UK       16UK 17 17 China    17China 18 18 USA       18USA 19 19 China    19China 20 20 Russia    20Russia

Let’s have a look at another example −

Example

 Live Demo

> Class<-LETTERS[1:20] > Rank<-sample(1:10,20,replace=TRUE) > df2<-data.frame(Class,Rank) > df2

Output

 Class Rank 1 A    2 2 B    4 3 C    4 4 D    6 5 E    7 6 F    10 7 G    10 8 H    5 9 I    9 10 J   6 11 K   1 12 L    8 13 M    10 14 N    7 15 O    5 16 P    7 17 Q    6 18 R    1 19 S    10 20 T    3


> df2$Class_Rank<-apply(df2,1,paste,collapse="_") > df2

Output

 Class Rank Class_Rank 1    A 2       A_ 2 2    B 4       B_ 4 3    C 4       C_ 4 4    D 6       D_ 6 5    E 7       E_ 7 6    F 10      F_10 7    G 10       G_10 8    H 5       H_ 5 9    I 9       I_ 9 10    J 6       J_ 6 11    K 1       K_ 1 12    L 8       L_ 8 13    M 10       M_10 14    N 7       N_ 7 15    O 5       O_ 5 16    P 7       P_ 7 17    Q 6       Q_ 6 18    R 1       R_ 1 19    S 10       S_10 20    T 3       T_ 3
Updated on: 2020-09-04T12:34:39+05:30

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements