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))