[英]Computing row-wise zscores in R dataframe
我的 dataframe 包含數字和字符列,如下所示。
> df
A B C D E G
a1 b1 c1 1 2 3
a2 b2 c2 4 5 6
...
我想使用 dplyr 計算數字列(D、E 和 G)的逐行 zscores。 我試過了:
> df %>% rowwise() %>% mutate_if(is.numeric, ~scale(., center=T, scale=T))
> A B C D E G
a1 b1 c1 NA NA NA
a2 b2 c2 NA NA NA
我無法理解為什么 NA 被退回。 非常感謝有關如何實現我想要做的任何輸入。
謝謝
使用base R
df[4:6] <- t(scale(t(df[4:6]), center = TRUE, scale = TRUE))
或者使用tidyverse
library(dplyr)
library(tidyr)
library(purrr)
df %>%
mutate(out = pmap(across(where(is.numeric)),
~ scale(c(...), center = TRUE, scale = TRUE)), .keep = 'unused') %>%
unnest_wider(out) %>%
mutate(across(D:G, c))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.