我有一个数据框,下面有三列:
下面是一些虚拟数据。
private let ItemFavoritesFilePath = "ItemFavorites.plist"
func LoadItemFavorites() -> Array<ItemFavorite>
{
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let docuDir = paths.firstObject as! String
let path = docuDir.stringByAppendingPathComponent(ItemFavoritesFilePath)
let dict = NSDictionary(contentsOfFile: path)
let dictitems : AnyObject? = dict?.objectForKey("favorites")
var favoriteItemsList = Array<ItemFavorite>()
if let arrayitems = dictitems as? NSArray
{
for var i = 0;i<arrayitems.count;i++
{
if let itemDict = arrayitems[i] as? NSDictionary
{
let ItemCode = itemDict.objectForKey("ItemCode") as? String
//get any additional
let ItemFavorite = ItemFavorite(item: ItemCode)
favoriteItemsList.append(ItemFavorite)
}
}
}
return favoriteItemsList
}
我希望在给定的一周内没有购买时添加cat.code<-c("a","a","a","b","b","b","c","d")
dol<-c(4,10,2,5,6,8,9,10)
wk.purch<-c(1,2,3,1,5,2,3,4)
fk.data<-data.frame(cat.code,dol,wk.purch)
> fk.data
cat.code dol wk.purch
1 a 4 1
2 a 10 2
3 a 2 3
4 b 5 1
5 b 6 5
6 b 8 2
7 c 9 3
8 d 10 4
的行。
所以,看一下dol = 0
,我想转换这个数据框,为第4周和第5周增加两行,cat.code= a
为0。我一直尝试使用dol
和expand.grid()
,但这对我不起作用。
谢谢大家!
答案 0 :(得分:4)
这是一个tidyr解决方案:
library(tidyr)
library(dplyr)
fk.data %>%
spread(cat.code, dol, fill = 0) %>%
gather(cat.code, dol, -wk.purch)
答案 1 :(得分:3)
您可以使用merge/expand.grid
transform(merge(expand.grid(cat.code= unique(fk.data$cat.code),
wk.purch=unique(fk.data$wk.purch)),
fk.data, all.x=TRUE), dol= replace(dol, is.na(dol), 0))
# cat.code wk.purch dol
#1 a 1 4
#2 a 2 10
#3 a 3 2
#4 a 4 0
#5 a 5 0
#6 b 1 5
#7 b 2 8
#8 b 3 0
#9 b 4 0
#10 b 5 6
#11 c 1 0
#12 c 2 0
#13 c 3 9
#14 c 4 0
#15 c 5 0
#16 d 1 0
#17 d 2 0
#18 d 3 0
#19 d 4 10
#20 d 5 0
或者使用data.table
,我们可以使用与CJ
类似的方法。我们转换了&#39; data.frame&#39;到&#39; data.table&#39; (setDT(fk.data
),并将关键列设置为&#39; cat.code&#39;和&#39; wk.purch&#39;。加入CJ
的输出并更改&#39; dol&#39;中的NA
值到&#39; 0&#39;。
library(data.table)#v1.9.5+
setDT(fk.data, key= c('cat.code', 'wk.purch'))[CJ(cat.code=unique(cat.code),
wk.purch=unique(wk.purch))][is.na(dol), dol:=0][]