Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.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中为每个唯一ID选择随机点_R - Fatal编程技术网

在R中为每个唯一ID选择随机点

在R中为每个唯一ID选择随机点,r,R,我之前的一个问题与这个问题非常相似 让我们创建这个随机数据集- df<- data.frame(ani_id = as.factor(1:10), x_data = rnorm(500), y_data=rnorm(500)) 我有唯一的ID 1到10。以及其他两列,其中包含x轴和y轴数据 我需要的是每个ID 5个随机点 我试过的是- df_sub<- do.call(rbind, by(df, df$ani_id, head, 5)) df_sub带有数据。表您可以使用动词.S

我之前的一个问题与这个问题非常相似

让我们创建这个随机数据集-

df<- data.frame(ani_id = as.factor(1:10), x_data = rnorm(500), y_data=rnorm(500))
我有唯一的ID 1到10。以及其他两列,其中包含x轴和y轴数据

我需要的是每个ID 5个随机点

我试过的是-

df_sub<- do.call(rbind, by(df, df$ani_id, head, 5))

df_sub带有
数据。表
您可以使用动词
.SD
(数据子集)按组应用函数。在你的情况下,你想要样品,比如说替换品


df我们可以在按“ani\u id”分组后使用
sample\n

library(dplyr)
df %>%
    group_by(ani_id) %>%
    sample_n(5)
# A tibble: 50 x 3
# Groups:   ani_id [10]
#   ani_id  x_data  y_data
#   <fct>    <dbl>   <dbl>
# 1 1       0.801  -1.19  
# 2 1      -0.255  -0.218 
# 3 1      -0.0337  0.924 
# 4 1      -0.287   0.0856
# 5 1      -1.47   -1.73  
# 6 2       0.916  -0.849 
# 7 2       0.620  -0.151 
# 8 2      -0.529   1.02  
# 9 2       0.0470  1.15  
#10 2      -0.904  -1.98  
# … with 40 more rows
库(dplyr)
df%>%
分组人(ani id)%>%
样本(5)
#一个tibble:50x3
#组别:ani_id[10]
#ani_id x_数据y_数据
#          
# 1 1       0.801  -1.19  
# 2 1      -0.255  -0.218 
# 3 1      -0.0337  0.924 
# 4 1      -0.287   0.0856
# 5 1      -1.47   -1.73  
# 6 2       0.916  -0.849 
# 7 2       0.620  -0.151 
# 8 2      -0.529   1.02  
# 9 2       0.0470  1.15  
#10 2      -0.904  -1.98  
#…还有40行
数据
set.seed(24)
df
library(dplyr)
df %>%
    group_by(ani_id) %>%
    sample_n(5)
# A tibble: 50 x 3
# Groups:   ani_id [10]
#   ani_id  x_data  y_data
#   <fct>    <dbl>   <dbl>
# 1 1       0.801  -1.19  
# 2 1      -0.255  -0.218 
# 3 1      -0.0337  0.924 
# 4 1      -0.287   0.0856
# 5 1      -1.47   -1.73  
# 6 2       0.916  -0.849 
# 7 2       0.620  -0.151 
# 8 2      -0.529   1.02  
# 9 2       0.0470  1.15  
#10 2      -0.904  -1.98  
# … with 40 more rows
set.seed(24)
df<- data.frame(ani_id = as.factor(1:10),
         x_data = rnorm(500), y_data=rnorm(500))