passing dataframe col name through cbind()
Try this:
cbind(scores[,1,drop = FALSE], scores[,2:3])
name round1 round2 1 Bob 40 5 2 Ron 30 6 3 Bud 20 4
Then do ?'[' to learn about 'drop'
On Tue, Nov 8, 2011 at 1:06 PM, Eric Rupley <erupley at umich.edu> wrote:
Hi all --- I note that the column name of the first column in a dataframe does not necessarily get passed on when using cbind (example below)? I'm looking for help in clarifying why this behavior occurs, and how I can get all col names, including the first, passed on to the result?while I suspect it's obvious and documented to the cognoscenti, it's puzzling me? Many thanks for any help on this... Eric
scores <- data.frame(name=c("Bob","Ron","Bud"),round1=c(40,30,20),round2=c(5,6,4)) #some toy data
scores
?name round1 round2 1 ?Bob ? ? 40 ? ? ?5 2 ?Ron ? ? 30 ? ? ?6 3 ?Bud ? ? 20 ? ? ?4
cbind(scores[,1],total=rowSums(scores[,2:3]),scores[,2:3])
?scores[, 1] total round1 round2 1 ? ? ? ? Bob ? ?45 ? ? 40 ? ? ?5 2 ? ? ? ? Ron ? ?36 ? ? 30 ? ? ?6 3 ? ? ? ? Bud ? ?24 ? ? 20 ? ? ?4
...first column renamed... ?yet this passes all column names:
cbind(scores[,1:3])
?name round1 round2 1 ?Bob ? ? 40 ? ? ?5 2 ?Ron ? ? 30 ? ? ?6 3 ?Bud ? ? 20 ? ? ?4
?but this doesn't:
cbind(scores[,1],scores[,2:3])
?scores[, 1] round1 round2 1 ? ? ? ? Bob ? ? 40 ? ? ?5 2 ? ? ? ? Ron ? ? 30 ? ? ?6 3 ? ? ? ? Bud ? ? 20 ? ? ?4 -- ?Eric Rupley ?University of Michigan, Museum of Anthropology ?1109 Geddes Ave, Rm. 4013 ?Ann Arbor, MI 48109-1079 ?erupley at umich.edu ?+1.734.276.8572
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Jim Holtman Data Munger Guru What is the problem that you are trying to solve? Tell me what you want to do, not how you want to do it.