Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner wanted: Create data frame and give colnames: R data.frame(..., colnames = c("a", "b", "c"))

Tags:

r

Is there an easier (i.e. one line of code instead of two!) way to do the following:

results <- as.data.frame(str_split_fixed(c("SampleID_someusefulinfo.countsA" , "SampleID_someusefulinfo.countsB" , "SampleID_someusefulinfo.counts"), "\\.", n=2))
names(results) <- c("a", "b")

Something like:

results <- data.frame(str_split_fixed(c("SampleID_someusefulinfo.countsA" , "SampleID_someusefulinfo.countsB" , "SampleID_someusefulinfo.counts"), "\\.", n=2), colnames = c("a", "b"))

I do this a lot, and would really love to have a way to have this in one line of code.

/data.table works too, if it's easier to do there than in base data.frame/

Clarifying:

My expected output (which is achieved by running the two lines of code at the top - AND I WANT IT TO BE ONE - THAT's IT!!!) is a result data frame of the structure:

results
                       a      b
1 SampleID_someusefulinfo countsA
2 SampleID_someusefulinfo countsB
3 SampleID_someusefulinfo  counts

What I would like to do is:

  1. CREATE the data frame from a matrix or with some content (for example the toy code of matrix(c(1,2,3,4),nrow=2,ncol=2) I provided in the first example I wrote)
  2. SPECIFY IN THAT SAME LINE what I would like the column names of my data frame to be
like image 929
dvanic Avatar asked Nov 29 '22 09:11

dvanic


1 Answers

Use setNames() around a data.frame

setNames(data.frame(matrix(c(1,2,3,4),nrow=2,ncol=2)), c("a","b"))
#  a b
#1 1 3
#2 2 4

?setNames:

a convenience function that sets the names on an object and returns the object

> setNames
function (object = nm, nm) 
{
    names(object) <- nm
    object
}
like image 88
SymbolixAU Avatar answered Dec 15 '22 13:12

SymbolixAU