我可以在没有“apply()"函数的情况下跨行应用 R 标准差吗? [英] Can I apply R standard deviation across rows without `apply()` function?
问题描述
library(tidyverse)
df <- tibble(col1 = c(5, 2), col2 = c(6, 4), col3 = c(9, 9))
# # A tibble: 2 x 3
# col1 col2 col3
# <dbl> <dbl> <dbl>
# 1 5 6 9
# 2 2 4 9
df %>% mutate(col4 = apply(.[, c(1, 3)], 1, sum))
df %>% mutate(col4 = rowSums(.[c(1, 3)], na.rm = TRUE))
最近 R 的 apply()
函数给我带来了麻烦.目前我将尽量减少它的使用并使用替代品.@akrun 告诉我我可以使用 rowSums()
而不是 apply()
作为示例,如上所示.
Lately R's apply()
function has been trouble for me. For the time being I'm going to minimize it's use and use alternatives. @akrun educated me that I could use rowSums()
instead of apply()
as shown above, as an example.
但是有没有一种方法可以应用跨列的标准偏差,就像我在下面所做的那样.显然我的 imaginary::rowSd
函数将无法工作.编的.
But is there a way to apply, say, standard deviation across columns, like I do below. Obviously my imaginary::rowSd
function is not going to work. It's made up.
df %>% mutate(col4 = apply(.[, c(1, 3)], 1, sd))
df %>% mutate(col4 = imaginary::rowSd(.[c(1, 3)], na.rm = TRUE))
不使用 apply()
的方法是什么?虽然我对这个包和 map()
函数知之甚少,但我在想 purrr.也许有一个更简单/更优雅的解决方案.
What is an approach that would work, without using apply()
? I'm thinking purrr although I've little knowledge on this package and the map()
functions. Maybe there's an even easier/elegant solution.
我应该提到我不能使用列名,因为我从中提取信息的数据库中的名称经常发生变化.我只能使用列号,因为相对列位置在我从中提取数据的数据库中不会改变.
I should've mentioned I can't use column names because the names often change in the database I pull my info from. I can only use column numbers, because relative column position doesn't change in the database I pull data from.
推荐答案
一个更简单的选择是 matrixStats
中的 rowSds
,但它只适用于 matrix
,因此将数据集的子集转换为 matrix
并应用 rowSds
An easier option is rowSds
from matrixStats
, but it works only on a matrix
, so convert the subset of dataset to matrix
and apply rowSds
library(matrixStats)
library(dplyr)
df %>%
mutate(col4 = rowSds(as.matrix(.[c(1, 3)])))
# A tibble: 2 x 4
# col1 col2 col3 col4
# <dbl> <dbl> <dbl> <dbl>
#1 5 6 9 2.83
#2 2 4 9 4.95
这篇关于我可以在没有“apply()"函数的情况下跨行应用 R 标准差吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!