- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combine two columns in R data frame with comma separation.
To combine two columns in R data frame with comma separation, we can use paste function with sep argument.
For Example, if we have two columns say X and Y in a data frame called df then we can combine the values of these two columns in a new column with comma separation by using the below mentioned command −
df$Combined<-paste(df$X,df$Y,sep=",")
Example 1
Following snippet creates a sample data frame −
x1<-sample(0:9,20,replace=TRUE) y1<-sample(0:9,20,replace=TRUE) df1<-data.frame(x1,y1) df1
The following dataframe is created
x1 y1 1 4 5 2 1 9 3 9 9 4 0 9 5 6 7 6 3 1 7 4 1 8 9 8 9 2 1 10 1 8 11 6 8 12 4 5 13 2 0 14 4 9 15 1 3 16 5 2 17 3 7 18 2 5 19 9 9 20 6 5
To create a new column of combined values in x1 and y1 with comma separation on the above created data frame, add the following code to the above snippet −
x1<-sample(0:9,20,replace=TRUE) y1<-sample(0:9,20,replace=TRUE) df1<-data.frame(x1,y1) df1$Combined<-paste(df1$x1,df1$y1,sep=",") df1
Output
If you execute all the above given snippets as a single program, it generates the following Output −
x1 y1 Combined 1 4 5 4,5 2 1 9 1,9 3 9 9 9,9 4 0 9 0,9 5 6 7 6,7 6 3 1 3,1 7 4 1 4,1 8 9 8 9,8 9 2 1 2,1 10 1 8 1,8 11 6 8 6,8 12 4 5 4,5 13 2 0 2,0 14 4 9 4,9 15 1 3 1,3 16 5 2 5,2 17 3 7 3,7 18 2 5 2,5 19 9 9 9,9 20 6 5 6,5
Example 2
Following snippet creates a sample data frame −
x2<-sample(LETTERS[1:26],20) y2<-sample(LETTERS[1:26],20) df2<-data.frame(x2,y2) df2
The following dataframe is created
x2 y2 1 T P 2 A I 3 P Y 4 F O 5 E G 6 I F 7 M D 8 L V 9 Z A 10 B L 11 S S 12 V W 13 Y H 14 Q K 15 K J 16 D U 17 J X 18 C E 19 N B 20 U Q
To create a new column of combined values in x2 and y2 with comma separation on the above created data frame, add the following code to the above snippet −
x2<-sample(LETTERS[1:26],20) y2<-sample(LETTERS[1:26],20) df2<-data.frame(x2,y2) df2$Combined_Col<-paste(df2$x2,df2$y2,sep=",") df2
Output
If you execute all the above given snippets as a single program, it generates the following Output −
x2 y2 Combined_Col 1 T P T,P 2 A I A,I 3 P Y P,Y 4 F O F,O 5 E G E,G 6 I F I,F 7 M D M,D 8 L V L,V 9 Z A Z,A 10 B L B,L 11 S S S,S 12 V W V,W 13 Y H Y,H 14 Q K Q,K 15 K J K,J 16 D U D,U 17 J X J,X 18 C E C,E 19 N B N,B 20 U Q U,Q