Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.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中两列值之间的随机值_R - Fatal编程技术网

获取R中两列值之间的随机值

获取R中两列值之间的随机值,r,R,我有一个数据框,它有两列: structure(list(lowage = c(45, 15, 9, 51, 22, 45, 4, 4, 9, 25), highage = c(50, 21, 14, 60, 24, 50, 8, 8, 14, 30)), .Names = c("lowage", "highage"), row.names = c(NA, 10L), class = "data.frame") 数据框看起来像: lowage highage 1 4

我有一个数据框,它有两列:

structure(list(lowage = c(45, 15, 9, 51, 22, 45, 4, 4, 9, 25), 
    highage = c(50, 21, 14, 60, 24, 50, 8, 8, 14, 30)), .Names = c("lowage", 
"highage"), row.names = c(NA, 10L), class = "data.frame")
数据框看起来像:

   lowage highage
1      45      50
2      15      21
3       9      14
4      51      60
5      22      24
6      45      50
7       4       8
8       4       8
9       9      14
10     25      30
我试图为两列之间的每一行获取一个随机数,并将其保存为第三列

我尝试了以下方法:

df$age <- sample(df$lowage:df$highage,1)

df$age我们可以使用
apply
MARGIN=1
(按行),在两列之间生成一个数字序列,然后使用
sample
从中选择任意一个数字

df$random_number <- apply(df, 1, function(x) sample(seq(x[1], x[2]), 1))

df

#   lowage highage random_number
#1      45      50            47
#2      15      21            21
#3       9      14             9
#4      51      60            55
#5      22      24            23
#6      45      50            47
#7       4       8             7
#8       4       8             8
#9       9      14            14
#10     25      30            27
for (i in 1:length(df$lowage)) {
 df$age[i] <- round(sample(df$lowage[i]:df$highage[i]),1)
}
Warning messages:
1: In df$age[i] <- round(sample(df$lowage[i]:df$highage[i]),  ... :
  number of items to replace is not a multiple of replacement length
df$random_number <- apply(df, 1, function(x) sample(seq(x[1], x[2]), 1))

df

#   lowage highage random_number
#1      45      50            47
#2      15      21            21
#3       9      14             9
#4      51      60            55
#5      22      24            23
#6      45      50            47
#7       4       8             7
#8       4       8             8
#9       9      14            14
#10     25      30            27
df$random_number <- mapply(function(x, y) sample(seq(x, y), 1), 
                    df$lowage, df$highage)