gpt4 book ai didi

r - 使用sample()创建一个新的data.frame变量,最大sample()值因行而异

转载 作者:行者123 更新时间:2023-12-04 15:44:03 27 4
gpt4 key购买 nike

我有一个 12071 行的数据框 foo 。我正在尝试,对于 foo 的每一行,根据 1:K 生成单个随机值,并将其插入到新列 L 中。例如,第一行应给出 1 到 5 之间的 L 值,第二行应给出 1 到 9 之间的值,第三个介于 1 和 3 之间,依此类推。这些值必须是整数,因此我尝试使用 sample() 。每行内该范围内的任何整数都有相同的选择概率。

我已经减少了代码中的列数,因为它们是不相关的,并且我在示例中遇到了数据包装问题。 A 列和 K 列是链接的,因此 A 列中的字符串在 K 列中始终具有相同的值。由于 A 列值不唯一,因此存在重复的 A/K 组合。

数据(减少列数):

A           B     C     D               E     F             G       ... K    
A011100 F 7 Partnered 4 40-49 Hrs 0.04075 5
A011200 M 7 Partnered 4 40-49 Hrs 0.13334 9
A011400 F 8 Non-partnered 2 30-39 Hrs 0.02310 3
A011500 F 4 Non-partnered 4 1-9 Hrs 0.94519 4
A012100 M 8 Partnered 4 40-49 Hrs 0.78114 4

我无法让我的代码工作。我无法弄清楚将新的最大值传递给 sample() 的逻辑,对于 data.frame 中的每一行,并在每一行中正确构造它。

我尝试过以下方法:

foo$L <- lapply(foo, sample(1:foo$K,1))

这给出了:

Error in match.fun(FUN) : 'sample(1:foo$K, 1)' is not a function, character or symbol In addition: Warning message: In 1:foo$K : numerical expression has 12071 elements: only the first used

然后

foo$L <- lapply(foo, function(x) sample(1:foo$K,1))

由此产生的错误是:

Error in $<-.data.frame(*tmp*, L, value = list(A = 1L, : replacement has 12 rows, data has 12071 In addition: There were 12 warnings (use warnings() to see them)

然后

foo$L <- replicate(nrow(foo), sample(foo, 1:foo$K,1))

这给了

There were 50 or more warnings (use warnings() to see the first 50)

最佳答案

我们可以使用sapply进行sample

df$L <- sapply(df$K, function(x) sample(x, 1))

# A B C K L
#1 A011100 F 7 5 1
#2 A011200 M 7 9 7
#3 A011400 F 8 3 2
#4 A011500 F 4 4 2
#5 A012100 M 8 4 1

取自?sample

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x.

因此,对于 df$K 的每个值,我们都会从 sapply 中的 1:x 中进行采样,然后随机选择其中一个值。

PS - 为了简单性和更好的可见性,我进一步减少了列。

关于r - 使用sample()创建一个新的data.frame变量,最大sample()值因行而异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49765367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com