【发布时间】:2019-05-17 19:15:20
【问题描述】:
我是“R”程序的新手,目前想要处理缺失值。 基本上,我有一个包含几列的数据集,并且“购买”列中缺少值。
我想根据缺失值的“Master_Category”列估算购买值的平均值。
(Python 代码)
# generate missing Purchase values
miss_Purch_rows = dataset['Purchase'].isnull()
# Check Purchase values from the grouping by the newly created Master_Product_Category column
categ_mean = dataset.groupby(['Master_Product_Category'])['Purchase'].mean()
# Impute mean Purchase value based on Master_Product_Category column
dataset.loc[miss_Purch_rows,'Purchase'] = dataset.loc[miss_Purch_rows,'Master_Product_Category'].apply(lambda x: categ_mean.loc[x])
我正在“R 程序”中寻找类似的代码,以通过均值估算缺失值并与另一列相关。
数据集的样本数据如下;
User_ID Product_ID Gender Age Occupation Marital_Status Master_Category Purchase
1 1000001 P00000142 F 0-17 10 0 345 13650
2 1000001 P00004842 F 0-17 10 0 3412 13645
3 1000001 P00025442 F 0-17 10 0 129 15416
4 1000001 P00051442 F 0-17 10 0 8170 9938
5 1000001 P00051842 F 0-17 10 0 480 2849
6 1000001 P00057542 F 0-17 10 0 345 NA
7 1000001 P00058142 F 0-17 10 0 3412 11051
8 1000001 P00058242 F 0-17 10 0 3412 NA
9 1000001 P00059442 F 0-17 10 0 6816 16622
10 1000001 P00064042 F 0-17 10 0 3412 8190
我试过了;
with(dataset, sapply(X = Purchase, INDEX = Master_Category, FUN = mean, na.rm = TRUE))
但它似乎不起作用。
【问题讨论】:
-
你能在R中使用
dput分享数据吗? -
我现在已经在问题中添加了数据
-
可以使用
reticulate包在R中使用Python -
R 中是否有函数来执行插补平均值?我努力了 ; with(dataset, sapply(X = Purchase, INDEX = Master_Category, FUN = mean, na.rm = TRUE)) 但它似乎不起作用
标签: r missing-data imputation