我面临一个小问题。
我有一个如下所示的表格,我想用" streches"创建一个新列。 1个值直到找到下一个2。
我应该创建一个: for(rowi in 1:totalnbofrow){}? 有更简单的方法吗?
Filen Nb Valu Valu2 Phase
File1 01 18.71 2.84
File1 02 18.68 2.85
File1 03 18.65 2.85 1
File1 04 18.62 2.86
File1 05 18.59 2.86
File1 06 18.56 2.86
File1 07 18.52 2.86 2
File1 08 18.49 2.86
File1 09 18.46 2.86
File1 10 18.44 2.86
File1 11 18.41 2.85 1
File1 12 18.38 2.86
File2 01 18.36 2.86
File2 02 18.34 2.86 1
File2 03 18.32 2.85
File2 04 18.30 2.86 2
File2 05 18.32 2.85
File2 06 18.32 2.85 1
File2 07 18.30 2.86
预期产出
Filen Nb Valu Valu2 Phase
File1 01 18.71 2.84
File1 02 18.68 2.85
File1 03 18.65 2.85 1
File1 04 18.62 2.86 1
File1 05 18.59 2.86 1
File1 06 18.56 2.86 1
File1 07 18.52 2.86 2
File1 08 18.49 2.86 2
File1 09 18.46 2.86 2
File1 10 18.44 2.86 2
File1 11 18.41 2.85 1
File1 12 18.38 2.86 1
File2 01 18.36 2.86 1
File2 02 18.34 2.86 1
File2 03 18.32 2.85 1
File2 04 18.30 2.86 2
File2 05 18.32 2.85 2
File2 06 18.32 2.85 1
File2 07 18.30 2.86 1
提前感谢你
答案 0 :(得分:1)
你可以尝试
library(zoo)
df$Phase[df$Phase==''] <- NA
df$newCol <- na.locf(df$Phase, na.rm=FALSE)
df$newCol
#[1] NA NA 1 1 1 1 2 2 2 2 1 1 1 1 1 2 2 1 1
或者,如果您的预期输出类似于@ eipi10的解释,则另一个选项是
do.call(pmax,c(list(as.numeric(df$Phase), 1), list(na.rm=TRUE)))
#[1] 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1
或者
rowSums(cbind((df$Phase==''), as.numeric(df$Phase)), na.rm=TRUE)
#[1] 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1
或者
library(data.table)
setDT(df)[Phase=='', Phase := '1'][]
df <- structure(list(Filen = c("File1", "File1", "File1", "File1",
"File1", "File1", "File1", "File1", "File1", "File1", "File1",
"File1", "File2", "File2", "File2", "File2", "File2", "File2",
"File2"), Nb = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L), Valu = c(18.71, 18.68, 18.65,
18.62, 18.59, 18.56, 18.52, 18.49, 18.46, 18.44, 18.41, 18.38,
18.36, 18.34, 18.32, 18.3, 18.32, 18.32, 18.3), Valu2 = c(2.84,
2.85, 2.85, 2.86, 2.86, 2.86, 2.86, 2.86, 2.86, 2.86, 2.85, 2.86,
2.86, 2.86, 2.85, 2.86, 2.85, 2.85, 2.86), Phase = c("", "",
"1", "", "", "", "2", "", "", "", "1", "", "", "1", "", "2",
"", "1", "")), .Names = c("Filen", "Nb", "Valu", "Valu2", "Phase"
), row.names = c(NA, -19L), class = "data.frame")