R extract data frame from list without prefixes in column names

20,633

Extract using [[ rather than [:

> newdf1 <- as.data.frame(result[['df1']])
> newdf1
  column1 Column2 Column3
1      NA      NA      NA

The difference is that [ extracts a list containing the requested component(s). [[ extracts the requested component directly (i.e. it retrieves the contents of that component of the list, not a list containing that component).

But as df1 already is a data frame, why not just do:

newdf1 <- result[['df1']]

? You don't need the as.data.frame() part.

Share:
20,633
Volder
Author by

Volder

Updated on March 25, 2020

Comments

  • Volder
    Volder about 4 years

    I place a data frame inside the list. Then when try to extract it back - I get all column names prefixed with list key for this data frame, is there a way to extract data frame exactly as it was passed initially?

    cols<-c("column1", "Column2", "Column3")
    df1<-data.frame(matrix(ncol = 3, nrow = 1))
    colnames(df1)<-cols
    df1
    
    result<-list()
    result['df1']<-list(df1)
    
    newdf1<-as.data.frame(result['df1'])
    newdf1
    

    Get as a result (column names are prefixed with df1):

    > cols<-c("column1", "Column2", "Column3")
    > df1<-data.frame(matrix(ncol = 3, nrow = 1))
    > colnames(df1)<-cols
    > df1
      column1 Column2 Column3
    1      NA      NA      NA
    > 
    > result<-list()
    > result['df1']<-list(df1)
    > 
    > newdf1<-as.data.frame(result['df1'])
    > newdf1
      df1.column1 df1.Column2 df1.Column3
    1          NA          NA          NA
    

    Of course, I can remove the prefixes manually, but probably there is a proper way to do this. Thanks!

  • Volder
    Volder about 11 years
    nice, in this case I don't even need type conversion as.data.frame() as it is already data.frame returned. Thx
  • Gavin Simpson
    Gavin Simpson about 11 years
    @Volder Yes, I just added that. Glad it helped.