我的資料看起來像這樣。如何按行(每個 Id)計算比例(sqrt 轉換)?這是一個包含超過 10 000 條記錄的大型資料集。
Id dogs cats birds fish
602 1 0 1 1
603 0 1 1 1
603 1 1 1 0
uj5u.com熱心網友回復:
在前面,我認為是這樣的:
sqrt(dat[,-1] / rowSums(dat[,-1]))
# Ap Ak Al Aj
# 1 0.5773503 0.0000000 0.5773503 0.5773503
# 2 0.0000000 0.5773503 0.5773503 0.5773503
# 3 0.5773503 0.5773503 0.5773503 0.0000000
步驟:
dat[,-1]
# Ap Ak Al Aj
# 1 1 0 1 1
# 2 0 1 1 1
# 3 1 1 1 0
rowSums(dat[,-1])
# [1] 3 3 3
dat[,-1] / rowSums(dat[,-1])
# Ap Ak Al Aj
# 1 0.3333333 0.0000000 0.3333333 0.3333333
# 2 0.0000000 0.3333333 0.3333333 0.3333333
# 3 0.3333333 0.3333333 0.3333333 0.0000000
uj5u.com熱心網友回復:
這是另一種方式 dplyr
library(dplyr)
df %>%
rowwise() %>%
mutate(across(starts_with("A"), ~sqrt(./sum(c_across(Ap:Aj)))))
Id Ap Ak Al Aj
<int> <dbl> <dbl> <dbl> <dbl>
1 602 0.577 0 0.577 0.577
2 603 0 0.577 0.577 0.577
3 603 0.577 0.577 0.577 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340143.html
標籤:r
上一篇:ggplot只有黑點,沒有顏色
