您可以尝试使用函数reshape
:
获取尽可能多的列,以匹配所有可能的项目:
new_df <- reshape(df, idvar="customer_code", timevar="items", v.names="items", direction="wide")
new_df
您可以使用 colnames(new_df)[-1] <- paste0("item", 1:(ncol(new_df)-1))
更改列名。
另一种选择是,如果您希望获得每个唯一客户所拥有的最大项目数量个列:
df_split <- split(df, df[, 1])
df_split <- lapply(df_split, reshape, idvar="customer_code", timevar="items", v.names="items", direction="wide")
max_item <- max(sapply(df_split, ncol))
df_split <- lapply(df_split, function(df){
if(ncol(df) < max_item) df <- cbind(df, matrix(NA, ncol=max_item - ncol(df)))
colnames(df)[-1] <- paste0("item", 1:(max_item-1))
return(df)
})
new_df <- do.call("rbind", df_split)
new_df
des_subcat1
中预期输出的NA
值对于客户 ID 为3.12E+12
的des_subcat
列中的articulo
并不合理。 - akrun