r - 将对象作为行添加到 R 中的数据框
问题描述
我有一个空的 DF:
CharactersDF <- data.frame(matrix(ncol = 7, nrow = 0))
我创建了一个新类:
RPGcharacter <- function(name, level, rpgClass, race, HP, attack, resist){
value <- list(name= name, level = level, rpgClass = rpgClass, HP = HP, attack = attack, resist = resist)
attr(value, "class") <- "RPGcharacter"
value
}
然后是新对象:
Artur <- RPGcharacter("Artur", 22, "Warlock", "Dwarf", 130, 12, 3)
如何在那个空的df中将对象添加为一行?我试过了:
CharactersDF <- rbind(CharactersDF, Artur)
但我得到了:
Warning messages:
1: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
replacement element 1 has 1 row to replace 0 rows
2: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
replacement element 2 has 1 row to replace 0 rows
3: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
replacement element 3 has 1 row to replace 0 rows
4: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
replacement element 4 has 1 row to replace 0 rows
5: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
replacement element 5 has 1 row to replace 0 rows
6: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
replacement element 6 has 1 row to replace 0 rows
7: In `[<-.data.frame`(`*tmp*`, 1, value = list(name = "Artur", level = 22, :
provided 6 variables to replace 1 variables
解决方案
正如 Ben 在他的评论中指出的那样,你想使用CharactersDF <- rbind(CharactersDF, Artur)
.
您在CharactersDF
and上使用 rbind 功能Artur
,因此您使用rbind()
. 您正在尝试使用 Python 风格的语法,其中句点表示您正在调用 object 的属性CharactersDF
。在这里,您要调用rbind()
这两个对象,然后将结果分配到您要存储的任何位置。