每個籃子可容納的水果總數爲10.對於每個籃子,如果數量爲10且缺少一個水果,我想爲該籃子添加一行說那個水果的數量是0。 以下是生成數據幀的代碼。爲每個缺失值的組添加一行
Basket <- c("A","A","B","B","C","C","C")
Fruit <- c("Apple","Orange","Apple","Orange","Orange","Apple", "Guava")
count <- c("5","5","7","3","2","6","4")
data <- data.frame(Basket,Fruit,count)
Basket Fruit count
1 A Apple 5
2 A Orange 5
3 B Apple 7
4 B Guava 3
5 C Orange 2
6 C Apple 6
7 C Guava 4
我想基本上像它看起來是這樣的:
Basket Fruit count
1 A Apple 5
2 A Orange 5
4 A Guava 0
5 B Apple 7
6 B Orange 0
7 B Guava 3
8 C Orange 2
9 C Apple 6
10 C Guava 4
不完全相信,如果循環將是一種有效的方法,但開放的建議。目標是爲每個水果在羣體中獲得準確的平均值。
Nvm。這工作! – rockboy23
關於不匹配屬性的抱怨可能是由於字符變量被視爲「因素」。嘗試在'data.frame'結構中添加'stringsAsFactors = FALSE'。或者更好的是,使用'tibble :: data_frame'來代替。 –