Booom...........

LabNotes and Random Thoughts...............

Saturday, July 18, 2015

combining the columns in a data.frame in R

There is a R markdown sharing website called RPubs but I tried putting the html code into blogger . The purpose here is to keep a note while exploring R. combinig the columns in a df
The question is how do I combine the columns in a dataframe I tried using dplyr , but I realized that I’m still a novice So here is a solution in using base r
Create a df
f = list("f1","f2","f3")
p = list("p1","p2","p3")
g = list("g1","g2","g3")
df = as.data.frame(cbind(phylum=p, family=f, genus=g))
print(df) 
##   phylum family genus
## 1     p1     f1    g1
## 2     p2     f2    g2
## 3     p3     f3    g3
 if it wasn't converted to a data.frame then this would have worked
 cbind( paste0(df[1,],"_",df[2,],"_",df[3,]))
 rbind( paste0(df[1,],"_",df[2,],"_",df[3,]))
# these two gives the same result
cbind( paste0(df[,1],"_",df[,2],"_",df[,3]))
cbind(paste0(df$phylum, "_", df$family, "_" , df$genus))
cbind(paste0(df$phylum, "_", df$family, "_" , df$genus))
##      [,1]      
## [1,] "p1_f1_g1"
## [2,] "p2_f2_g2"
## [3,] "p3_f3_g3"
# these two give the same results
rbind( paste0(df[,1],"_",df[,2],"_",df[,3]))
rbind(paste0(df$phylum, "_", df$family, "_" , df$genus))
rbind(paste0(df$phylum, "_", df$family, "_" , df$genus))
##      [,1]       [,2]       [,3]      
## [1,] "p1_f1_g1" "p2_f2_g2" "p3_f3_g3"

Another easy way I found was :
 as.matrix(lapply(df, function(x) paste(x, collapse="_") )) 
 [,1]
 phylum "p1_p2_p3" 
 family "f1_f2_f3" 
 genus "g1_g2_g3"

No comments: