R包学习——reshape包中melt、cast、merge函数用法

本文详细介绍了R语言reshape包中的melt、cast和merge函数,包括如何将数据转化为适合重塑的格式,如何进行数据重塑或聚合,以及如何通过共同列进行数据框的合并。同时,文章提到了merge函数与dplyr包中的join函数(inner_join、left_join、right_join、full_join)的对应关系,并提供了使用示例。
摘要由CSDN通过智能技术生成

本文使用的例子皆为官方example,在Rstudio中使用 ?+函数名 即可查看。

1. melt:Melt an object into a form suitable for easy casting.

> head(tips)
  total_bill  tip    sex smoker day   time size
1      16.99 1.01 Female     No Sun Dinner    2
2      10.34 1.66   Male     No Sun Dinner    3
3      21.01 3.50   Male     No Sun Dinner    3
4      23.68 3.31   Male     No Sun Dinner    2
5      24.59 3.61 Female     No Sun Dinner    4
6      25.29 4.71   Male     No Sun Dinner    4
> head(melt(tips))
Using sex, smoker, day, time as id variables
     sex smoker day   time   variable value
1 Female     No Sun Dinner total_bill 16.99
2   Male     No Sun Dinner total_bill 10.34
3   Male     No Sun Dinner total_bill 21.01
4   Male     No Sun Dinner total_bill 23.68
5 Female     No Sun Dinner total_bill 24.59
6   Male     No Sun Dinner total_bill 25.29
> 
> head(airquality)
  ozone solar.r wind temp month day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6
> names(airquality) <- tolower(names(airquality))
> head(melt(airquality, id=c("month", "day")))
  month day variable value
1     5   1    ozone    41
2     5   2    ozone    36
3     5   3    ozone    12
4     5   4    ozone    18
5     5   5    ozone    NA
6     5   6    ozone    28
> 
> head(ChickWeight) 
  weight time chick diet
1     42    0     1    1
2     51    2     1    1
3     59    4     1    1
4     64    6     1    1
5     76    8     1    1
6     93   10     1    1
> names(ChickWeight) <- tolower(names(ChickWeight))
> head(melt(ChickWeight, id=2:4))
  time chick diet variable value
1    0     1    1   weight    42
2    2     1    1   weight    51
3    4     1    1   weight    59
4    6     1    1   weight    64
5    8     1    1   weight    76
6   10     1    1   weight    93

2. cast:Cast a molten data frame into the reshaped or aggregated form you want

> names(airquality) <- tolower(names(airquality))
> aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE)
> head(aqm)
  month day variable value
1     5   1    ozone    41
2     5   2    ozone    36
3     5   3    ozone    12
4     5   4    ozone    18
5     5   6    ozone    28
6     5   7    ozone    23


> str(cast(aqm, day ~ month ~ variable))
 num [1:31, 1:5, 1:4] 41 36 12 18 NA 28 23 19 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值