[英]Should I be using unnest_wider and rowMeans to get the average of a list column?
我有一個簡單的數據集。 行名是一個有意義的索引,第 1 列有一個值列表。 我最終想要的是每個行名稱的列表的平均值。
現在的樣子:
行名 | 年 |
---|---|
108457 | [1200, 1200, 1540, 1890] |
237021 | [1600, 1270, 1270] |
我最終希望它看起來像:
行名 | 年 |
---|---|
108457 | 列表的平均值 |
237021 | 列表的平均值 |
目前,我正在嘗試使用unnest_wider(years)
。 我的計划是之后使用rowMeans()
來查找未嵌套行的平均值。 然后我可以將行名和平均值與我的主數據集合並,所以我不太關心刪除新列。
但是,整個過程需要一段時間,而且我在使用unnest_wider
時遇到了一些問題。 目前,當我嘗試時:
unnest_wider(dataset, colname)
我收到以下錯誤:
as_indices_impl()
中的錯誤:。 必須使用有效的下標向量對列進行子集化。 ✖ 下標有錯誤的類型data.frame<years:list>
。 ℹ 必須是數字或字符。
當我嘗試時:
unnest_wider(colname)
我的計算機一直在無休止地運行,看起來它在計數......它不會停止,我必須退出應用程序才能終止處理。
我以前曾嘗試直接應用rowMeans
、使用mean(df$ColName)
和使用apply(ColName, mean)
。
我想知道是否有更有效的方法?
可能是我一開始就不應該創建列表。 現在看起來是這樣,因為我將它從這種格式轉換而來:
A列 | B列 |
---|---|
108457 | 1200 |
108457 | 1200 |
108457 | 1540 |
237021 | 1600 |
108457 | 1890年 |
237021 | 1270 |
我使用pivot_wide
r 轉換它,然后使用as.data.frame.(t(dataset))
我應該嘗試直接從這種格式中獲取平均值嗎? 如果是這樣,我該怎么做?
對於每一行中的向量,您可以使用sapply
遍歷每一行來計算平均值,然后只返回每個行名稱的平均值。
df$years <- sapply(df$years, mean, na.rm = TRUE)
Output
years
108457 1457.5
237021 1380.0
數據
df <- structure(list(years = structure(list(c(1200, 1200, 1540, 1890
), c(1600, 1270, 1270)), class = "AsIs")), row.names = c("108457",
"237021"), class = "data.frame")
或者我們可以使用data.table
來獲取平均值,如果您的數據看起來像后者,長格式數據集。
library(data.table)
as.data.table(df2)[, list(ColumnB = mean(ColumnB)), by = ColumnA]
Output
ColumnA ColumnB
1: 108457 1457.5
2: 237021 1435.0
數據
df2 <- structure(list(ColumnA = c(108457L, 108457L, 108457L, 237021L,
108457L, 237021L), ColumnB = c(1200L, 1200L, 1540L, 1600L, 1890L,
1270L)), class = "data.frame", row.names = c(NA, -6L))
如果您的原始數據看起來像后一個表中的那樣,您可以簡單地根據ColumnA
按組找到平均值:
數據
df <- read.table(text = "ColumnA ColumnB
108457 1200
108457 1200
108457 1540
237021 1600
108457 1890
237021 1270", header = TRUE)
基地 R
aggregate(df$ColumnB, list(df$ColumnA), FUN=mean)
# Group.1 x
# 1 108457 1457.5
# 2 237021 1435.0
Dplyr
library(dplyr)
df %>%
group_by(ColumnA) %>%
summarise(mean_years = mean(ColumnB))
# ColumnA mean_years
# <int> <dbl>
#1 108457 1458.
#2 237021 1435
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.