nak*_*120 0 r matrix dataframe
我有一个数据帧如下:
Destination User User_Price
A a 5
A b 4
B c 6
B a 5
C b 4
C d 7
Run Code Online (Sandbox Code Playgroud)
我想将其转换为一个矩阵,显示用户点击的目标,如下所示:
User User_Price A B C
a 5 1 1 0
b 4 1 0 1
c 6 0 1 0
d 7 0 0 1
Run Code Online (Sandbox Code Playgroud)
dplyr和tidyr包的一种方法是:
library(dplyr)
library(tidyr)
count(foo, User, User_Price, Destination) %>%
spread(key = Destination, value = n, fill = 0)
# User User_Price A B C
# (fctr) (int) (dbl) (dbl) (dbl)
#1 a 5 1 1 0
#2 b 4 1 0 1
#3 c 6 0 1 0
#4 d 7 0 0 1
Run Code Online (Sandbox Code Playgroud)
如果需要矩阵,可以将此结果(数据框)转换为矩阵.
数据
foo <- structure(list(Destination = structure(c(1L, 1L, 2L, 2L, 3L,
3L), .Label = c("A", "B", "C"), class = "factor"), User = structure(c(1L,
2L, 3L, 1L, 2L, 4L), .Label = c("a", "b", "c", "d"), class = "factor"),
User_Price = c(5L, 4L, 6L, 5L, 4L, 7L)), .Names = c("Destination",
"User", "User_Price"), class = "data.frame", row.names = c(NA,
-6L))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |