我已经对数据进行了子集化,因此更容易展示我正在尝试做的事情。我正在尝试为“MaxRounds”列中的值创建一个新行的数据框。起初 MaxRounds 在这样的列中:
library(dplyr);library(tidyr);library(splitstackshape)
structure(list(power = c(0.800962297001584, 0.804719517260326,
0.808410477932415, 0.812036218849852, 0.803164810470566, 0.815597767274311
), nights = c(20L, 20L, 20L, 20L, 19L, 20L), sites = c(78L, 79L,
80L, 81L, 81L, 82L), NonRoundedMaxRounds = c(3, 3, 3, 3, 3.15789473684211,
3), MaxRounds = c(3, 3, 3, 3, 3, 3)), row.names = c(NA, 6L), class = "data.frame")
然后我创建了依赖于 MaxRounds 列的新行 = 创建依赖于 MaxRounds 数量的重复行。例如,如果 MaxRounds 为 2,则创建 1-2 行,如果 MaxRounds 为 5,则创建 5 行)。
该代码创建一个唯一的 ID 行名称:x、x.1、x.2、x.3 等。
data = expandRows(data, "MaxRounds")
structure(list(power = c(0.800962297001584, 0.800962297001584,
0.800962297001584, 0.804719517260326, 0.804719517260326, 0.804719517260326
), nights = c(20L, 20L, 20L, 20L, 20L, 20L), sites = c(78L, 78L,
78L, 79L, 79L, 79L), NonRoundedMaxRounds = c(3, 3, 3, 3, 3, 3
)), row.names = c("1", "1.1", "1.2", "2", "2.1", "2.2"), class = "data.frame")
然后,我根据行名创建了一个新列:
data$RowID = rownames(data)
structure(list(power = c(0.800962297001584, 0.800962297001584,
0.800962297001584, 0.804719517260326, 0.804719517260326, 0.804719517260326
), nights = c(20L, 20L, 20L, 20L, 20L, 20L), sites = c(78L, 78L,
78L, 79L, 79L, 79L), NonRoundedMaxRounds = c(3, 3, 3, 3, 3, 3
), RowID = c("1", "1.1", "1.2", "2", "2.1", "2.2")), row.names = c("1",
"1.1", "1.2", "2", "2.1", "2.2"), class = "data.frame")
接下来,我尝试将具有相同 x 值(尽管有小数点)的所有行组合在一起并按顺序编号。例如:
- 1、1.1、1.2 = 1、2、3
- 2, 2.1, 2.1 = 1, 2, 3
我正在尝试使用“RowID”列进行分组:
data %>% group_by(RowID) %>% mutate(id = row_number())
但我得到这个错误: