Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Transforming R dataframe by applying function rowwise and create (possibly) larger columns

$
0
0

I'm trying to transform a dataframe (tibble) by using each row as function arguments and create a new column out of it, which is possibly bigger than the number of arguments. Consider the following example, where I have some sample observations:

library(dplyr)
library(stringi)

observations <- c("110", "11011", "1100010")

df <- tibble(obs = observations) %>%
    transmute(
        Failure = stri_count(obs, fixed = "0"),
        Success = stri_count(obs, fixed = "1")
    )

df is then:

# A tibble: 3 x 2
  Failure Success
    <int>  <int>
1       1      2
2       1      4
3       4      3

I would like to take every row and use that for calculating a bunch of values, and save each result vector in a new column. For example I would like to do:

p_values = pgrid <- seq(from = 0, to = 1, length.out = 11)

df %>%
    rowwise() %>%
    transmute(
        p = p_values,
        likelihood = dbinom(Success,
            size = Failure + Success,
            prob = p_values
        )
    )

Error: Column `p` must be length 1 (the group size), not 11

And get something like:

# A tibble: 4 x 11
  p_values likelihood_1 likelihood_2 likelihood_3
     <float>  <float>     <float>      <float>
1       0      ...         ...           ...
2       0.1    ...         ...           ...
...     ...    ...         ...           ...
10      0.9    ...         ...           ...
11      1      ...         ...           ...     

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>