Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.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
R 取消Pivot数据帧-获取原始数据序列_R - Fatal编程技术网

R 取消Pivot数据帧-获取原始数据序列

R 取消Pivot数据帧-获取原始数据序列,r,R,我需要清理以下数据帧 df <- data.frame(metric=c(10,20,30,40,NA), cnt=c(1,2,1,2,2)) > df metric cnt 1 10 1 2 20 2 3 30 1 4 40 2 5 NA 2 这是tidyr的一个用例吗?如果是,基于tidyr的解决方案也会有所帮助。我们可以使用rep 反向rle有一个函数inverse.rle。请参见帮助: metric 1

我需要清理以下数据帧

df <- data.frame(metric=c(10,20,30,40,NA), cnt=c(1,2,1,2,2))
> df
  metric cnt
1     10   1
2     20   2
3     30   1
4     40   2
5     NA   2
这是tidyr的一个用例吗?如果是,基于tidyr的解决方案也会有所帮助。

我们可以使用rep

反向rle有一个函数inverse.rle。请参见帮助:

  metric
1     10 
2     20  
3     20  
4     30  
5     40  
6     40  
7     NA  
8     NA 
df1 <- data.frame(metric = rep(df$metric, df$cnt))
df <- data.frame(metric=c(10,20,30,40,NA), cnt=c(1,2,1,2,2))
names(df) <- c("values", "lengths")
inverse.rle(df) # or
data.frame(metric=inverse.rle(df))