我已经对数据进行了子集化,因此更容易展示我正在尝试做什么。但我试图创建的是一个数据框,它创建一个依赖于“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 值(尽管有小数点)的所有行组合在一起并按顺序编号。例如:
我正在尝试使用“RowID”列进行分组:
data %>% group_by(RowID) %>% mutate(id = row_number())
但我收到此错误:
Row ID
可以使用 完成by_group
或独立创建唯一的dplyr
,这里是使用的示例mtcars
mtcars %>% group_by(cyl) %>% mutate(
id = row_number()
)
# Groups: cyl [3]
mpg cyl disp hp drat wt qsec vs am gear carb id
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
1 21 6 160 110 3.9 2.62 16.5 0 1 4 4 1
2 21 6 160 110 3.9 2.88 17.0 0 1 4 4 2
3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1 1
4 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1 3
5 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2 1
6 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1 4
没有grouping
,
mtcars %>% mutate(
id = row_number()
)
mpg cyl disp hp drat wt qsec vs am gear carb id
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 1
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 2
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 3
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 4
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 5
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 6
row_number()
按组或不按顺序对每一行进行编号。例如,在第4行的grouped
例子有id=3
,因为它是在第3行group
的6 cyl(inders)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句