如何通过NA`s分离包含NA的列?

1 numbers r dataframe na

这是我第一次提问,所以请宽大:)

我觉得这很简单.我有一个data.frame,它由一列"Time"组成.它看起来像这样:

-------------------------
> head(Times,10)
   Times
1     NA
2  0.448
3  0.130
4     NA
5     NA
6  0.462
7  0.427
8  0.946
9  0.227
10    NA
>
------------------------
Run Code Online (Sandbox Code Playgroud)

这个想法是,第一个NA表示序列的开始,因此,跟随时间应来自相同的标签.到达下一个NA条目后,序列结束.

我现在想要创建一个新的data.frame,它将NA之间的数字转换为列,并按行分隔序列.

  Time1 Time2 Time3 Time4
1 0.448 0.130 0.123 
2 0.462 0.427 0.946 0.227
>
---------------------------------
Run Code Online (Sandbox Code Playgroud)

你能帮我吗?

Rol*_*and 5

Times <- read.table(text = "Times
1     NA
2  0.448
3  0.130
4     NA
5     NA
6  0.462
7  0.427
8  0.946
9  0.227
10    NA", header = TRUE)

#identify values that belong together
Times$ind <- cumsum(is.na(Times$Times)) %/% 2 + 1

Times <- na.omit(Times) #remove NA values

#identify columns
Times$col <- unlist(tapply(Times$ind, factor(Times$ind), seq_along))

#reshape to wide format 
reshape(Times, timevar = "col", idvar = "ind", direction = "wide")
#  ind Times.1 Times.2 Times.3 Times.4
#2   1   0.448   0.130      NA      NA
#6   2   0.462   0.427   0.946   0.227
Run Code Online (Sandbox Code Playgroud)

我用基地R来玩.如果你需要更高效的东西,你应该使用package data.table.