Mutate column as input to sample

旧城冷巷雨未停 提交于 2021-01-29 12:14:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!