![](/img/trans.png)
[英]Efficient way to move specific columns and rows of a matrix at the same time in R
[英]Is there an efficient way to group a datatable by unique rows and columns at the same time in R?
我有一個這樣的數據表:
【數據概覽:】【1】【1】:https://i.stack.imgur.com/WabXJ.png
[我希望最終結果變成:][2] [2]:https://i.stack.imgur.com/wSEan.png
到目前為止,此代碼為每個變量生成了正確的值,但是,它並沒有很好地堆疊在 4x4 表中:
data <- data_raw %>%
mutate(Område = as.factor(data_raw$Område),
yield = as.numeric(`Yield (%)`),
yield_range =as.factor(case_when(yield <= 4.25 ~"3.00 - 4.25",
yield <= 5.50 ~"4.30 - 5.50",
yield <= 6.75 ~"5.55 - 6.75",
yield <= 8.00 ~"5.60 - 8,00"
)))
data_group <- data %>%
group_by(data_group$Område, data_group$yield_range) %>%
summarize(no = n())
[產生這個結果:][3] [3]:https://i.stack.imgur.com/9cfNX.png
有沒有一種簡單的方法可以重新排列最后一張表以類似於我在 [2] 中想要的結果?
您可以創建一個將類別作為范圍的新列。
data_raw <- within(data_raw, {
Yield.cat <- NA
Yield.cat[`Yield (%)` <= 4.25] <- "3.00-4.25"
Yield.cat[`Yield (%)` > 4.25 & `Yield (%)` <= 5.50] <- "4.25-5.50"
Yield.cat[`Yield (%)` > 5.50 & `Yield (%)` <= 6.75] <- "5.50-6.75"
Yield.cat[`Yield (%)` > 6.75] <- "6.75-8.00"
})
並轉換成頻率表
out <- as.data.frame.matrix(table(data_raw$Yield.cat, data_raw$Område))
但是,通過上述嘗試,您可以創建一個頻率表
library(dplyr)
data <- data_raw %>%
mutate(Område = as.factor(data_raw$Område),
yield = as.numeric(`Yield (%)`),
yield_range =as.factor(case_when(yield <= 4.25 ~"3.00 - 4.25",
yield <= 5.50 ~"4.30 - 5.50",
yield <= 6.75 ~"5.55 - 6.75",
yield <= 8.00 ~"5.60 - 8,00"
)))
out <- as.data.frame.matrix(table(data$yield_range, data$Område))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.