【发布时间】:2018-04-12 14:54:25
【问题描述】:
我有一个包含两列的数据框:
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)
这给了我以下错误:
Error in `$<-.data.frame`(`*tmp*`, age, value = c(47L, 50L, 49L, 48L, :
replacement has 6 rows, data has 795
In addition: Warning messages:
1: In df$lowage:dfhighage :
numerical expression has 795 elements: only the first used
2: In dflowage:df$highage :
numerical expression has 795 elements: only the first used
我尝试了一个 for 循环:
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 中看到每一行的值,但我不确定此警告是否对列有影响。
【问题讨论】:
标签: r