是否有辅助函数可以使此代码在 tibble 上更清晰?
Is there an helper function to make this code cleaner on tibble?
我需要对其中一列生成的序列求和。我是这样做的:
test <- tibble::tibble(
x = c(1,2,3)
)
test %>% dplyr::mutate(., s = plyr::aaply(x, .margins = 1, .fun = function(x_i){sum(seq(x_i))}))
有没有更简洁的方法来做到这一点?有没有一些辅助函数,构造可以让我减少这个:
plyr::aaply(x, .margins = 1, .fun = function(x_i){sum(seq(x_i))})
我正在寻找一个通用的解决方案,这里 sum 和 seq 只是一个例子。也许真正的问题是我确实想在元素而不是所有向量上执行函数。
这是我的真实案例:
test <- tibble::tibble(
x = c(1,2,3),
y = c(0.5,1,1.5)
)
d <- c(1.23, 0.99, 2.18)
test %>% mutate(., s = (function(x, y) {
dn <- dnorm(x = d, mean = x, sd = y)
s <- sum(dn)
s
})(x,y))
test %>% plyr::ddply(., c("x","y"), .fun = function(row) {
dn <- dnorm(x = d, mean = row$x, sd = row$y)
s <- sum(dn)
s
})
我想通过以连续方式而不是矢量化方式改变函数来做到这一点。
具体例子直接应用cumsum
test %>%
mutate(s = cumsum(x))
对于遍历行序列的一般情况,我们可以使用map
test %>%
mutate(s = map_dbl(row_number(), ~ sum(seq(.x))))
# A tibble: 3 x 2
# x s
# <dbl> <dbl>
#1 1 1
#2 2 3
#3 3 6
更新
对于更新的数据集,使用 map2
,因为我们使用数据集 'x' 和 'y' 列中 dnorm
中的相应参数
test %>%
mutate(V1 = map2_dbl(x, y, ~ dnorm(d, mean = .x, sd = .y) %>%
sum))
# A tibble: 3 x 3
# x y V1
# <dbl> <dbl> <dbl>
#1 1 0.5 1.56
#2 2 1 0.929
#3 3 1.5 0.470
我需要对其中一列生成的序列求和。我是这样做的:
test <- tibble::tibble(
x = c(1,2,3)
)
test %>% dplyr::mutate(., s = plyr::aaply(x, .margins = 1, .fun = function(x_i){sum(seq(x_i))}))
有没有更简洁的方法来做到这一点?有没有一些辅助函数,构造可以让我减少这个:
plyr::aaply(x, .margins = 1, .fun = function(x_i){sum(seq(x_i))})
我正在寻找一个通用的解决方案,这里 sum 和 seq 只是一个例子。也许真正的问题是我确实想在元素而不是所有向量上执行函数。
这是我的真实案例:
test <- tibble::tibble(
x = c(1,2,3),
y = c(0.5,1,1.5)
)
d <- c(1.23, 0.99, 2.18)
test %>% mutate(., s = (function(x, y) {
dn <- dnorm(x = d, mean = x, sd = y)
s <- sum(dn)
s
})(x,y))
test %>% plyr::ddply(., c("x","y"), .fun = function(row) {
dn <- dnorm(x = d, mean = row$x, sd = row$y)
s <- sum(dn)
s
})
我想通过以连续方式而不是矢量化方式改变函数来做到这一点。
具体例子直接应用cumsum
test %>%
mutate(s = cumsum(x))
对于遍历行序列的一般情况,我们可以使用map
test %>%
mutate(s = map_dbl(row_number(), ~ sum(seq(.x))))
# A tibble: 3 x 2
# x s
# <dbl> <dbl>
#1 1 1
#2 2 3
#3 3 6
更新
对于更新的数据集,使用 map2
,因为我们使用数据集 'x' 和 'y' 列中 dnorm
中的相应参数
test %>%
mutate(V1 = map2_dbl(x, y, ~ dnorm(d, mean = .x, sd = .y) %>%
sum))
# A tibble: 3 x 3
# x y V1
# <dbl> <dbl> <dbl>
#1 1 0.5 1.56
#2 2 1 0.929
#3 3 1.5 0.470