[英]Using “apply” functions across multiple data frames
我在多個數據幀之間使用Apply函數(我認為這是執行以下操作的正確方法)時遇到問題。
一些示例數據(3個不同的數據幀,但我正在處理的問題超過50個):
biz <- data.frame(
country = c("england","canada","australia","usa"),
businesses = sample(1000:2500,4))
pop <- data.frame(
country = c("england","canada","australia","usa"),
population = sample(10000:20000,4))
restaurants <- data.frame(
country = c("england","canada","australia","usa"),
restaurants = sample(500:1000,4))
這是我最終想要做的:
1)根據所包含的變量,從最大到最小對飲食數據幀進行排序
dataframe <- dataframe[order(dataframe$VARIABLE,)]
2)然后創建一個向量變量,該變量為我提供每個變量的排名
dataframe$rank <- 1:nrow(dataframe)
3)然后創建另一個數據框,該數據框的一列國家/地區和每個感興趣變量的排名與其他列一樣。 看起來像(這里的排名不是真實的):
country.rankings <- structure(list(country = structure(c(5L, 1L, 6L, 2L, 3L, 4L), .Label = c("brazil",
"canada", "england", "france", "ghana", "usa"), class = "factor"),
restaurants = 1:6, businesses = c(4L, 5L, 6L, 3L, 2L, 1L),
population = c(4L, 6L, 3L, 2L, 5L, 1L)), .Names = c("country",
"restaurants", "businesses", "population"), class = "data.frame", row.names = c(NA,
-6L))
所以我猜想有一種方法可以將這些數據幀中的每一個都放到一個列表中,例如:
lib <- c(biz, pop, restaurants)
然后對其進行一次不適用於1)排序,2)創建等級變量和3)為每個國家/地區的每個變量(企業數量,人口規模,餐廳數量)創建排名矩陣或數據框架。 我遇到的問題是,當我嘗試按變量排序時,編寫lapply函數對每個數據幀進行排序會遇到問題:
sort <- lapply(lib,
function(x){
x <- x[order(x[,2]),]
})
返回錯誤信息:
Error in `[.default`(x, , 2) : incorrect number of dimensions
因為我正在嘗試將列標題應用於列表。 但是,當每個數據框的變量名稱都不同時,我還要如何解決這個問題(但要記住,國家名稱是一致的)
(也很想知道如何使用plyr來使用它)
理想情況下,我會為此推薦data.table
。 但是,這是使用data.frame
的快速解決方案,請嘗試以下操作:
步驟1:創建所有data.frames的列表
varList <- list(biz,pop,restaurants)
步驟2:將所有內容合並到一個data.frame中
temp <- varList[[1]]
for(i in 2:length(varList)) temp <- merge(temp,varList[[i]],by = "country")
第三步:獲得排名:
cbind(temp,apply(temp[,-1],2,rank))
您可以根據需要刪除不想要的列!
cbind(temp[,1:2],apply(temp[,-1],2,rank))[,-2]
希望這可以幫助!!
totaldatasets <- c('biz','pop','restaurants')
totaldatasetslist <- vector(mode = "list",length = length(totaldatasets))
for ( i in seq(length(totaldatasets)))
{
totaldatasetslist[[i]] <- get(totaldatasets[i])
}
totaldatasetslist2 <- lapply(
totaldatasetslist,
function(x)
{
temp <- data.frame(
country = totaldatasetslist[[i]][,1],
countryrank = rank(totaldatasetslist[[i]][,2])
)
colnames(temp) <- c('country', colnames(x)[2])
return(temp)
}
)
Reduce(
merge,
totaldatasetslist2
)
輸出-
country businesses population restaurants
1 australia 3 3 3
2 canada 2 2 2
3 england 1 1 1
4 usa 4 4 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.