问题
I want create a distribution using the sample()
function with the probability of each value defined by a data.frame()
column. When I try the code below however it produces the error:
Error in sample.int(length(x), size, replace, prob) :
incorrect number of probabilities
I'm guessing this is because mutate is passing the entire column and not just one integer. Can anyone help me with this?
library(dplyr)
input = data.frame(input = 1:100)
output = input %>% mutate(output =
sum(
sample(0:1,
10,
replace = T,
prob = c(input, 100-input)
)))
回答1:
I have determined that the solution was to use the rowwise()
function in the pipe expression:
library(dplyr)
input = data.frame(input = 1:100)
output = input %>% rowwise() %>% mutate(output =
sum(
sample(0:1,
100,
replace = T,
prob = c(input, 1)
)))
来源:https://stackoverflow.com/questions/57617305/mutate-column-as-input-to-sample