简体   繁体   English

自动逐行使用数据框的功能

[英]Automatically rowwise a function for dataframe usage

I have a function**: 我有一个功能**:

do_thing <- function(x) {
    return(x + runif(1, 0, 100))
}

That I'd like to apply to my data: 我想将其应用于我的数据:

df <- tibble(x = 1:10)

Preferably with mutate : 最好使用mutate

set.seed(1)
df %>% 
    mutate(y = do_thing(x))

The function, however, is not performing as expected: 但是,该功能未按预期执行:

#       x y
# 1     1 27.55087
# 2     2 28.55087
# 3     3 29.55087
# 4     4 30.55087
# 5     5 31.55087
# 6     6 32.55087
# 7     7 33.55087
# 8     8 34.55087
# 9     9 35.55087
# 10   10 36.55087

I actually want the function to apply in a rowwise fashion: 我实际上希望函数以行方式应用:

df %>% 
    rowwise() %>% 
    mutate(y = do_thing(x))

#       x  y
# 1     1  38.21239
# 2     2  59.28534
# 3     3  93.82078
# 4     4  24.16819
# 5     5  94.83897
# 6     6 100.46753
# 7     7  73.07978
# 8     8  70.91140
# 9     9  15.17863
# 10   10  30.59746

Is there a way that I might be able to rewrite my function so that it is flexible and can automatically default to rowwise while still working with a single input (ie., do_thing(100) )? 有没有办法我可以重写我的函数,使其灵活并且可以在仍使用单个输入( do_thing(100) )的情况下自动默认为按行?

** actual function is a lot more complex ** 实际功能要复杂得多

Instead of getting the runif for 1 observation, we can specify the n as the number of rows ( n() ) of the dataset 我们可以将n指定为数据集的行数( n() ),而不是获取用于1个观察的runif

set.seed(24)
df %>%
     mutate(y = x + runif(n(), 0, 100))
# A tibble: 10 x 2
#       x          y
#   <int>      <dbl>
# 1     1  46.952549
# 2     2  61.939816
# 3     3  94.972191
# 4     4 102.282408
# 5     5   8.780258
# 6     6  63.793740
# 7     7  80.331417
# 8     8  32.874240
# 9     9  39.073652
#10    10  83.346670

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM