Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建一列,表示在R中被分成20个偶数组的数据帧_R_Dataframe - Fatal编程技术网

创建一列,表示在R中被分成20个偶数组的数据帧

创建一列,表示在R中被分成20个偶数组的数据帧,r,dataframe,R,Dataframe,我使用R试图在我的数据框中创建一个名为df的列,该列将数据拆分为20个偶数组,新列group每行都有相应的组。我的有序数据示例如下所示: preds ground_truth 65378 0.000002975379 0 27082 0.000004721652 0 26890 0.000006613435 1 130498 0.000007634303 0 173319

我使用R试图在我的数据框中创建一个名为
df
的列,该列将数据拆分为20个偶数组,新列
group
每行都有相应的组。我的有序数据示例如下所示:

                preds ground_truth
65378  0.000002975379            0
27082  0.000004721652            0
26890  0.000006613435            1
130498 0.000007634303            0
173319 0.000007834359            0
20039  0.000009482496            0
64722  0.000009482496            0
53924  0.000009482496            0
165543 0.000009482496            0
我以前也问过类似的问题,也有类似的答案,但由于某些原因,这些解决方案不起作用。其他答案如下:

我的解决方案是使用切割:

  df$group <- cut(index(df), 20, labels = FALSE)

使用一些模块化数学怎么样

如果我们有一个129844行的数据帧:

df 6493 6492 6492 6492 6492 6492 6492 6492 6492 6492 6492 6493 6492 6492 6492 6492 6492 6492 6492 6492 6493 6492 6492 6492

显然,129844不能被20平均整除,因此我们有4个组,其中包含6493个成员。

index函数从何而来?@jdobres来自Zoodos
cut(as.numeric(rownames(df)),20,labels=F)
软件包。如果你能分享一个可复制的例子,这也会很有帮助(示例数据、代码和输出)。在当前编写的代码中,您的代码应该按预期工作,因此必须关闭其他功能。@geds133
cut(As.numeric(rownames(dat)),20,labels=F)
对我来说很好。谢谢!这会考虑到排序还是被洗牌?当我尝试运行此命令时,我会出现以下错误:“替换有0行,数据有129844”@geds133为什么?使用
nrow(df)可以得到什么
?如果您的数据帧实际上被称为
df
,并且有129844行,那么这应该可以工作。在我的示例中尝试一下。
structure(list(preds = c(0.00000297537922317814, 
0.00000472165221855588, 
0.0000066134351160987, 0.00000763430272198875, 0.00000783435945631941, 
0.00000948249581302744, 0.00000948249581314139, 0.00000948249581314247, 
0.00000948249581314704, 0.0000094824958131879), ground_truth = 
structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = 
"factor")), .Names = c("preds", 
"ground_truth"), row.names = c("65378", "27082", "26890", "130498", 
"173319", "20039", "64722", "53924", "165543", "168952"), class = 
"data.frame")