R 如何通过重复某些特定行来更改数据帧?
我想重复前面观察到的行,其中列0位于行非零值d之前。因此,我将得到一行,其中交替的行是d值为零的行,然后是d值为非零的行。值为零的行必须是以前观察到的行 我想要的输出是:R 如何通过重复某些特定行来更改数据帧?,r,R,我想重复前面观察到的行,其中列0位于行非零值d之前。因此,我将得到一行,其中交替的行是d值为零的行,然后是d值为非零的行。值为零的行必须是以前观察到的行 我想要的输出是: a b c d 5015 3.49 1059.500 0.00 5023 2.50 6056.000 2.50 5024 3.00 1954.500 3.00 5026 3.49 1163.833
a b c d
5015 3.49 1059.500 0.00
5023 2.50 6056.000 2.50
5024 3.00 1954.500 3.00
5026 3.49 1163.833 0.00
5037 2.50 6797.000 2.50
5038 3.00 2109.000 3.00
5040 2.50 4521.000 2.50
5041 3.33 2469.000 3.33
我们可以创建一个自定义函数
f
,它将交错第一行。在cumsum(d==0)
为等于0的值创建索引时拆分。最后,我们结合do.call(rbind,…)
。我添加了一个可选的行。name我们可以创建一个自定义函数f
,它将交错第一行。在cumsum(d==0)
为等于0的值创建索引时拆分。最后,我们结合do.call(rbind,…)
。我添加了一个可选的”行。名称包数据。表的分组方式在这里很有用:
f <- function(x) x[c(rbind(rep(1,nrow(x)-1), 2:nrow(x))),]
`row.names<-`(do.call(rbind, lapply(split(df1, cumsum(df1$d == 0)), f)), NULL)
# a b c d
# 1 5015 3.49 1059.500 0.00
# 2 5023 2.50 6056.000 2.50
# 3 5015 3.49 1059.500 0.00
# 4 5024 3.00 1954.500 3.00
# 5 5026 3.49 1163.833 0.00
# 6 5037 2.50 6797.000 2.50
# 7 5026 3.49 1163.833 0.00
# 8 5038 3.00 2109.000 3.00
# 9 5026 3.49 1163.833 0.00
# 10 5040 2.50 4521.000 2.50
# 11 5026 3.49 1163.833 0.00
# 12 5041 3.33 2469.000 3.33
库(data.table)
DF包数据。表的分组方式在这里很有用:
f <- function(x) x[c(rbind(rep(1,nrow(x)-1), 2:nrow(x))),]
`row.names<-`(do.call(rbind, lapply(split(df1, cumsum(df1$d == 0)), f)), NULL)
# a b c d
# 1 5015 3.49 1059.500 0.00
# 2 5023 2.50 6056.000 2.50
# 3 5015 3.49 1059.500 0.00
# 4 5024 3.00 1954.500 3.00
# 5 5026 3.49 1163.833 0.00
# 6 5037 2.50 6797.000 2.50
# 7 5026 3.49 1163.833 0.00
# 8 5038 3.00 2109.000 3.00
# 9 5026 3.49 1163.833 0.00
# 10 5040 2.50 4521.000 2.50
# 11 5026 3.49 1163.833 0.00
# 12 5041 3.33 2469.000 3.33
库(data.table)
以下是一些其他交错技巧,供大家参考:以下是一些其他交错技巧,供大家参考:不要重复你的问题我没有解决方案不要重复你的问题我没有解决方案
library(data.table)
DF <-fread(" a b c d
5015 3.49 1059.500 0.00
5023 2.50 6056.000 2.50
5024 3.00 1954.500 3.00
5026 3.49 1163.833 0.00
5037 2.50 6797.000 2.50
5038 3.00 2109.000 3.00
5040 2.50 4521.000 2.50
5041 3.33 2469.000 3.33")
DF[ #find indices:
DF[, {ind <- .I[rep(1L, (.N - 1) * 2)] #first repeat the first index
ind[c(FALSE, TRUE)] <- .I[-1] #then replace every second repeat with the other indices
ind
}, by = cumsum(abs(d) < .Machine$double.eps^0.5)][["V1"]] #group by the different d = 0 rows,
#beware of floating point errors if you have calculated d
] #subset with the indices
# a b c d
# 1: 5015 3.49 1059.500 0.00
# 2: 5023 2.50 6056.000 2.50
# 3: 5015 3.49 1059.500 0.00
# 4: 5024 3.00 1954.500 3.00
# 5: 5026 3.49 1163.833 0.00
# 6: 5037 2.50 6797.000 2.50
# 7: 5026 3.49 1163.833 0.00
# 8: 5038 3.00 2109.000 3.00
# 9: 5026 3.49 1163.833 0.00
# 10: 5040 2.50 4521.000 2.50
# 11: 5026 3.49 1163.833 0.00
# 12: 5041 3.33 2469.000 3.33