合并不同维度的列表元素 [英] merge list elements which are different dimensions r

查看:113
本文介绍了合并不同维度的列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个df:

df= data.frame(year=c(rep(2018,4),rep(2017,3)),Area=c(1:4,1:3),P=1:7,N=1:7)

我想将其按年份划分,然后将所有内容再次合并在一起,这样我就可以将年份视为每个区域的列.为了做到这一点,我进行拆分和合并:

I want to split it by years, and then merge everything together again so I can see years as columns for each area. In order to do this, I am splitting and merging:

s=split(df,df$year)
m=merge(s[[1]][,2:4],[s[[2]][,2:4],by='Area',all=1)
colnames(m)=c('area','P2018','C2018','P2017','C2017')

我确信有一种更有效的方法,尤其是当我包含其他年份的数据时,出错的可能性非常高.

I am sure there is a more efficient way, expecially as the possibility for errors is very high once I include data from other years.

有什么建议吗?

推荐答案

我们可以将gather数据转换为长格式,但不包括yearArea列,unite year然后是spread宽格式.

We can gather data to long form excluding year and Area column, unite the year and then spread it to wide format.

library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -year, -Area) %>%
  unite(key, key, year, sep = "") %>%
  spread(key, value)

#  Area N2017 N2018 P2017 P2018
#1    1     5     1     5     1
#2    2     6     2     6     2
#3    3     7     3     7     3
#4    4    NA     4    NA     4

这篇关于合并不同维度的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆