我有一个空的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
答案 0 :(得分:1)
正如Ben在评论中指出的那样,您想使用CharactersDF <- rbind(CharactersDF, Artur)
。
您正在CharactersDF
和Artur
上使用rbind函数,因此您使用rbind()
。您正在尝试使用Python风格的语法,其中句点表示您正在调用对象CharactersDF
的属性。在这里,您要在两个对象上调用rbind()
,然后将结果分配到要存储的任何位置。
答案 1 :(得分:1)
尽管rbind解决方案有效,但请注意数据类型和数据结构。空的CharactersDF是包含逻辑类型的数据框
> CharactersDF <- data.frame(matrix(ncol = 7, nrow = 0))
> str(CharactersDF)
'data.frame': 0 obs. of 7 variables:
$ X1: logi
$ X2: logi
Artur是具有数字和字符类型的列表
> Artur <- RPGcharacter("Artur", 22, "Warlock", "Dwarf", 130, 12, 3)
> str(Artur)
List of 6
$ name : chr "Artur"
$ level : num 22
$ rpgClass: chr "Warlock"
$ HP : num 130
$ attack : num 12
$ resist : num 3
- attr(*, "class")= chr "RPGcharacter"
接着rbind
,数据类型再次更改为数值和因子。
> CharactersDF <- rbind(CharactersDF, Artur)
> str(CharactersDF)
'data.frame': 1 obs. of 6 variables:
$ name : Factor w/ 1 level "Artur": 1
$ level : num 22
$ rpgClass: Factor w/ 1 level "Warlock": 1
$ HP : num 130
$ attack : num 12
$ resist : num 3
确定您需要的类型并与它们一致地工作,或者根据需要故意强迫它们,这样会更安全。
要创建具有预设类型的空数据框,请选中Create an empty data.frame