melt 宽边长; dcast 长边宽
library(reshape2)
x <- data.frame(k1 = c(NA, NA, 3, 4, 5), k2 = c(1, NA, NA,
4, 5), data = 1:5)
y <- data.frame(k1 = c(NA, 2, NA, 4, 5), k2 = c(NA, NA, 3,
4, 5), data = 1:5)
res1 <- merge(x, y, by = "k1")
knitr::kable(head(res1))
k1 |
k2.x |
data.x |
k2.y |
data.y |
4 |
4 |
4 |
4 |
4 |
5 |
5 |
5 |
5 |
5 |
NA |
1 |
1 |
NA |
1 |
NA |
1 |
1 |
3 |
3 |
NA |
NA |
2 |
NA |
1 |
NA |
NA |
2 |
3 |
3 |
res2 <- merge(x, y, by = c("k1", "k2"))
knitr::kable(head(res2))
k1 |
k2 |
data.x |
data.y |
4 |
4 |
4 |
4 |
5 |
5 |
5 |
5 |
NA |
NA |
2 |
1 |
names(airquality) <- tolower(names(airquality))
knitr::kable(head(airquality))
ozone |
solar.r |
wind |
temp |
month |
day |
41 |
190 |
7.4 |
67 |
5 |
1 |
36 |
118 |
8.0 |
72 |
5 |
2 |
12 |
149 |
12.6 |
74 |
5 |
3 |
18 |
313 |
11.5 |
62 |
5 |
4 |
NA |
NA |
14.3 |
56 |
5 |
5 |
28 |
NA |
14.9 |
66 |
5 |
6 |
aql <- melt(airquality)
## No id variables; using all as measure variables
knitr::kable(head(aql))
variable |
value |
ozone |
41 |
ozone |
36 |
ozone |
12 |
ozone |
18 |
ozone |
NA |
ozone |
28 |
aql <- melt(airquality, id.vars = c("month", "day"))
knitr::kable(head(aql))
month |
day |
variable |
value |
5 |
1 |
ozone |
41 |
5 |
2 |
ozone |
36 |
5 |
3 |
ozone |
12 |
5 |
4 |
ozone |
18 |
5 |
5 |
ozone |
NA |
5 |
6 |
ozone |
28 |
aqw <- dcast(aql, month + day ~ variable)
knitr::kable(head(aqw))
month |
day |
ozone |
solar.r |
wind |
temp |
5 |
1 |
41 |
190 |
7.4 |
67 |
5 |
2 |
36 |
118 |
8.0 |
72 |
5 |
3 |
12 |
149 |
12.6 |
74 |
5 |
4 |
18 |
313 |
11.5 |
62 |
5 |
5 |
NA |
NA |
14.3 |
56 |
5 |
6 |
28 |
NA |
14.9 |
66 |
knitr::kable(head(airquality))
ozone |
solar.r |
wind |
temp |
month |
day |
41 |
190 |
7.4 |
67 |
5 |
1 |
36 |
118 |
8.0 |
72 |
5 |
2 |
12 |
149 |
12.6 |
74 |
5 |
3 |
18 |
313 |
11.5 |
62 |
5 |
4 |
NA |
NA |
14.3 |
56 |
5 |
5 |
28 |
NA |
14.9 |
66 |
5 |
6 |
d1 <- dcast(aql, month ~ variable)
## Aggregation function missing: defaulting to length
knitr::kable(d1)
month |
ozone |
solar.r |
wind |
temp |
5 |
31 |
31 |
31 |
31 |
6 |
30 |
30 |
30 |
30 |
7 |
31 |
31 |
31 |
31 |
8 |
31 |
31 |
31 |
31 |
9 |
30 |
30 |
30 |
30 |
d2 <- dcast(aql, month ~ variable, fun.aggregate = mean, na.rm = TRUE)
knitr::kable(d2)
month |
ozone |
solar.r |
wind |
temp |
5 |
23.61538 |
181.2963 |
11.622581 |
65.54839 |
6 |
29.44444 |
190.1667 |
10.266667 |
79.10000 |
7 |
59.11538 |
216.4839 |
8.941935 |
83.90323 |
8 |
59.96154 |
171.8571 |
8.793548 |
83.96774 |
9 |
31.44828 |
167.4333 |
10.180000 |
76.90000 |
网友评论