我正在嘗試將資料幀串列從 ggeffects 物件轉換為一個資料幀,以便在 ggplot2 中更好地使用它。這是我正在嘗試的一個簡單示例:
library(ggeffects)
library(dplyr)
data(efc)
fit <- lm(barthtot ~ c12hour neg_c_7 c161sex c172code, data = efc)
full <- ggpredict(fit)
df <- bind_rows(full, .id="id")
但這給了我以下錯誤:
錯誤:無法回收c12hour(尺寸 35)以匹配neg_c_7(尺寸 12)。
我是 R 和 Stackoverflow 的新手,所以我希望這一切都清楚。謝謝!
uj5u.com熱心網友回復:
我不完全理解您的目標,但在串列中系結資料框的一種方法是使用do.call(bind_rows, thelist):
do.call(bind_rows, full)
# Predicted values of Total score BARTHEL INDEX
# c12hour
c12hour | Predicted | 95% CI
------------------------------------
0 | 75.44 | [73.26, 77.63]
35 | 66.58 | [64.91, 68.25]
70 | 57.71 | [55.81, 59.61]
100 | 50.11 | [47.55, 52.68]
170 | 32.38 | [27.73, 37.03]
# c161sex
c12hour | Predicted | 95% CI
------------------------------------
1 | 63.96 | [60.57, 67.35]
2 | 65.00 | [63.11, 66.90]
# c172code
c12hour | Predicted | 95% CI
------------------------------------
1 | 64.06 | [61.01, 67.10]
2 | 64.78 | [63.12, 66.43]
3 | 65.49 | [62.32, 68.67]
# neg_c_7
c12hour | Predicted | 95% CI
------------------------------------
6 | 78.17 | [75.11, 81.22]
10 | 68.98 | [67.14, 70.81]
14 | 59.79 | [57.88, 61.69]
20 | 46.00 | [42.04, 49.97]
28 | 27.63 | [20.31, 34.95]
Adjusted for:
* neg_c_7 = 11.84
* c161sex = 1.76
* c172code = 1.97
但是,此表單并未顯示所有資料和列。要顯示所有這些,您可以使用as.data.frame()或as_tibble()。
do.call(bind_rows, full) |> as_tibble()
# A tibble: 52 × 6
x predicted std.error conf.low conf.high group
<dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 0 75.4 1.12 73.3 77.6 c12hour
2 5 74.2 1.06 72.1 76.3 c12hour
3 10 72.9 1.01 70.9 74.9 c12hour
4 15 71.6 0.965 69.8 73.5 c12hour
5 20 70.4 0.925 68.6 72.2 c12hour
6 25 69.1 0.893 67.4 70.9 c12hour
7 30 67.8 0.868 66.1 69.5 c12hour
8 35 66.6 0.851 64.9 68.2 c12hour
9 40 65.3 0.842 63.7 67.0 c12hour
10 45 64.0 0.843 62.4 65.7 c12hour
# … with 42 more rows
然后可以使用 ggplot 來創建繪圖。例如:
do.call(bind_rows, full) |>
ggplot(aes(x =x, y = predicted, col = group))
geom_point()
結果圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484948.html
