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!
1 Answer
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.