我有以下數據框架,我想用top_products中尚未出現在該行中的第一個product_id替換NA。爲了給出一些背景,這些是產品推薦。如何將函數應用於每一行並返回R中的行?
雖然我對plyr和sapply有一些經驗,但我正在努力找出實現這一目標的正確方法。
我認爲下面的代碼本身就說明了。
> head(recs_with_na)
V1 V2 V3 V4
148 1227 1213 <NA> <NA>
249 1169 1221 <NA> <NA>
553 1227 1162 <NA> <NA>
732 1227 1162 <NA> <NA>
765 1227 1162 <NA> <NA>
776 1227 1162 <NA> <NA>
> top_products
product_id count
21 1162 7917
65 1213 4839
19 1160 4799
11 1152 3543
34 1175 3423
75 1227 2719
2 1143 2396
13 1154 2168
> fill_nas_with_top <- function(data, top_products) {
+ top_products_copy <- top_products
+ mydata <- data
+ #mydata <- as.data.frame(data)
+ for (i in 1:4) {
+ if (is.na(mydata[,i])) {
+ mydata[,i] <- top_products_copy[1,1]
+ top_products_copy <- top_products_copy[-1,]
+
+ }
+ else {
+ top_products_copy <- top_products_copy[top_products_copy[,1] != mydata[,i],]
+ }
+ }
+ return(mydata)
+ }
> sapply(recs_with_na, fill_nas_with_top, top_products)
Show Traceback
Rerun with Debug
Error in `[.default`(mydata, , i) : incorrect number of dimensions
recs_with_na的列被傳遞逐個添加到函數fill_nas_with_top。但是你想要一個接一個地傳遞行。 – cryptomanic