我的数据框包含Product_Id和FrontOfficeUser_Id。
Data_Achat=data.frame(ID_Achat,ID_Prod)
> Data_Achat[1:10,]
ID_Achat ID_Prod
1 1349 433
2 1349 405
3 1349 451
4 4890 405
5 4890 405
6 4890 416
7 4890 416
8 4890 388
9 4890 464
10 4890 416
然后我想得到一个新的数据框,在每一行显示ID_Achat及其对应的ID_Prod。换句话说,对于这个例子,我想这样:
1 1349 433 405 451
2 4890 405 405 416 416 388 464 416
如何获得此结果?
谢谢!
答案 0 :(得分:0)
以下是将数据放入data.frame的方法:
split_data <- split(df$ID_Prod, df$ID_Achat)
pasted <- lapply(split_data,paste,collapse=" ")
as.data.frame(do.call(rbind,pasted))
V1
1349 433 405 451
4890 405 405 416 416 388 464 416
修改强>
以下是返回ID列的方法:
split_data <- split(df$ID_Prod, df$ID_Achat)
pasted <- lapply(split_data,paste,collapse=" ")
df <- as.data.frame(do.call(rbind,pasted))
df_final <- cbind(ID_Achat=rownames(df),df)
colnames(df_final)[2] <- "ID_Prod"
df_final
ID_Achat ID_Prod
1349 1349 433 405 451
4890 4890 405 405 416 416 388 464 416
答案 1 :(得分:0)
library(dplyr)
library(tidyr)
Data_Achat %>%
group_by(ID_Achat) %>%
mutate(rn = row_number()) %>%
ungroup() %>%
spread(rn, ID_Prod)
编辑:
Data_Achat <- data.frame(ID_Achat = c(rep(1349, 3), rep(4890, 7)), ID_Prod = c(433, 405, 451, 405, 405, 416, 416, 388, 464, 416))
Data_Achat2 <- Data_Achat %>%
+ group_by(ID_Achat) %>%
+ mutate(rn = row_number()) %>%
+ ungroup() %>%
+ spread(rn, ID_Prod)
> Data_Achat2[1,]
# A tibble: 1 x 8
ID_Achat `1` `2` `3` `4` `5` `6` `7`
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1349 433 405 451 NA NA NA NA