Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将data.frame展开为不同的行_R_Dataframe - Fatal编程技术网

将data.frame展开为不同的行

将data.frame展开为不同的行,r,dataframe,R,Dataframe,我试图弄清楚如何将R中的data.frame扩展为不同的行。我的意思是使用startyear和toyear变量来创建一个年度data.frame,其中id按照从=startyear到=endyear的顺序为每个不同的年份复制 我有一个data.frame示例: testdat <- data.frame(id=seq(1,10), startyear=c(1946,1960,1965,1976,1955,1999,2013,1981,1983,1995)

我试图弄清楚如何将R中的data.frame扩展为不同的行。我的意思是使用startyear和toyear变量来创建一个年度data.frame,其中id按照从=startyear到=endyear的顺序为每个不同的年份复制

我有一个data.frame示例:

testdat <- data.frame(id=seq(1,10),
           startyear=c(1946,1960,1965,1976,1955,1999,2013,1981,1983,1995)
           )

testdat$endyear <- testdat$startyear+sample(1:10,10,replace=TRUE)
我期望的结果是这样的:

id year
1  1946
1  1947
1  1948
1  1949
1  1950
1  1951
2  1960
.  ....

任何关于如何做到这一点的建议都是非常好的。谢谢。

您希望从宽格式转换为长格式

软件包中的
聚集
功能可以实现这一点


在.

中有一个全面的示例,您希望将宽格式转换为长格式

软件包中的
聚集
功能可以实现这一点


在包装中有一个全面的例子。

melt
从包装中
重塑
可以处理以下问题:

library(reshape)
melt(testdat, id.vars  = c("id"))

从包装中提取的
melt
重塑
可以处理以下问题:

library(reshape)
melt(testdat, id.vars  = c("id"))
试试“哈德利诗”,即
dplyr
tidyr

library(dplyr)
library(tidyr)
testdat %>% 
  group_by(id) %>%
  expand(year=full_seq(c(startyear, endyear), 1))
# Source: local data frame [64 x 2]
# Groups: id [10]
# 
#       id  year
#    (int) (dbl)
# 1      1  1946
# 2      1  1947
# 3      1  1948
# 4      1  1949
# 5      1  1950
# 6      1  1951
# 7      1  1952
# 8      2  1960
# 9      2  1961
# 10     3  1965
# ..   ...   ...
试试“哈德利诗”,即
dplyr
tidyr

library(dplyr)
library(tidyr)
testdat %>% 
  group_by(id) %>%
  expand(year=full_seq(c(startyear, endyear), 1))
# Source: local data frame [64 x 2]
# Groups: id [10]
# 
#       id  year
#    (int) (dbl)
# 1      1  1946
# 2      1  1947
# 3      1  1948
# 4      1  1949
# 5      1  1950
# 6      1  1951
# 7      1  1952
# 8      2  1960
# 9      2  1961
# 10     3  1965
# ..   ...   ...

相似的。所以对于ex,答案是肯定的<代码>库(data.table);setDT(testdat)[,list(year=startyear:endyear),by=id]
类似。所以对于ex,答案是肯定的<代码>库(data.table);setDT(testdat)[,list(year=startyear:endyear),by=id]感谢您在答案中提供了一个工作代码。感谢您在答案中提供了一个工作代码。