我有一个包含七个列的数据框(Dataset_Events),其中两个是eventInfo_ea和eventInfo_el。我想在eventInfo_ea ='add to cart'的行中删除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答复,其长度与data.frame相同
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
答案 0 :(得分:2)
尝试一下:
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更改为空)。
答案 1 :(得分:2)
我实际上找到了一个可行的解决方案。我跳过了定义函数的整个过程,只使用了下面的代码就可以了
Dataset_Events[ Dataset_Events["eventInfo_ea"]=="add to cart", ]["eventInfo_el"] <- NA
仍然高兴地听到为什么大家的建议似乎根本没有修改我的数据集。还是非常感谢!!!
答案 2 :(得分:1)
我认为问题在于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)