0

I want to have data frame with two columns, one of them is a character one and the second one is list.
All I need is to have two functions:
- createEmptyDf() which creates such data frame with no rows
- addRowToDf(df, valueCharacter, valueList) which adds a row to df and then returns it

I had some problem with both variables, especially when I was adding a row to an empty df.
Could someone tell me how to make it simply?

Example:

df <- createEmptyDf()  
nrow(df) # should return 0  
df <- addRowToDf(df, "AAA", list("A", 1, "B"))  
nrow(df) # should return 1   
df[1, "varCharacter"] # should return "AAA"  
df[1, "varList"] # should return list("A", 1, "B") 

I've finally know what was wrong - when I want to add new row the valueList should be like I(list(list(values))):

ANSWER

createEmptyDf <- function(){
  df <- data.frame(varCharacter = character(0), varList = I(list()))
  return(df)
}

 addRowToDf <- function(df, valueCharacter, valueList){
   row <- data.frame(varCharacter = valueCharacter, varList = I(list(valueList)))
   df <- rbind(df, row)
   return(df)
}

df <- createEmptyDf()
df <- addRowToDf (df, "AAAA", list("A", 2 ,3))
Tomek Tarczynski
  • 2,785
  • 8
  • 37
  • 43
  • Please provide some example data, without that it is hard to help you. – Paul Hiemstra May 06 '13 at 10:55
  • I'm not sure I understand the question. `createEmptyDf` sounds like the standard `data.frame` and `addRowToDf` sounds like `rbind`. Am I missing something? – Thomas May 06 '13 at 11:19
  • @Thomas: I thought so too, but nevertheless I had problems. df <- data.frame(varCharacter = character(0), varList = list()) Such code doesn't create empty df with 2 columns. – Tomek Tarczynski May 06 '13 at 11:28

0 Answers0