我有一个包含七列的数据帧(Dataset_Events(,其中两列是eventInfo_ea和eventInfo_el。我想在eventInfo_ea="添加到购物车"的行中删除eventInfo_el的单元格值。请参阅下面的代码。
Remove = function(Dataset_Events, eventInfo_ea, eventInfo_el){
if(Dataset_Events[["eventInfo_ea"]]=="add to cart"){
Dataset_Events[["eventInfo_el"]] <- NULL
}
}
sapply(Dataset_Events, Remove)
不幸的是,R给了我以下错误消息:"Dataset_Events[["eventInfo_ea"]]中出错:下标越界"数据帧的尺寸为713478 x 7。有人能解释为什么以及如何修复它吗?
如果我只是运行If条件本身,我会得到一个与数据帧相同长度的正确TRUE/FALSE回复
Dataset_Events[["eventInfo_ea"]]=="add to cart"
这里是两个相关列的示例数据集(两列都有类因子(:
eventInfo_ea eventInfo_el
1 click thumbnail
2 click description
3 click hero image
4 click open size dropdown
5 click hero image
6 click hero image
7 click hero image
8 click description
9 click open size dropdown
10 click hero image
11 click hero image
12 click hero image
13 click hero image
14 click description
15 click open reviews
16 click hero image
17 click open reviews
18 click description
19 add to wishlist hero image
20 click hero image
21 click hero image
22 add to cart hero image
试试这个:
Remove = function(Dataset_Events){
ind = Dataset_Events[["eventInfo_ea"]] == "add to cart"
Dataset_Events[["eventInfo_el"]][ind] = NA
return (Dataset_Events)
}
Remove(Dataset_Events)
我从函数中删除了第二个和第三个参数(您似乎没有使用它们?(。正如您所注意到的,Dataset_Events[["eventInfo_ea"]]=="add to cart"
为您提供了一个逻辑向量,因此它应该用于索引要设置为NA
的行(我从NULL更改为NULL,因为这会带来问题(。
我认为问题在于Dataset_Events[["eventInfo_el"]]
返回了一个因子。在这种情况下,最好使用相同。
Remove = function(Dataset_Events, eventInfo_ea, eventInfo_el){
if(identical(as.character(Dataset_Events[["eventInfo_ea"]]),"add to cart")){
Dataset_Events[["eventInfo_el"]] <- NULL
}
}
sapply(Dataset_Events, Remove)
我实际上找到了一个有效的解决方案。我跳过了定义函数的整个部分,只使用了下面的代码,它就起到了的作用
Dataset_Events[ Dataset_Events["eventInfo_ea"]=="add to cart", ]["eventInfo_el"] <- NA
尽管如此,我仍然很高兴听到为什么你们所有人的建议似乎根本没有修改我的数据集。不过非常感谢!!!