我很難在多個資料幀的函式中獲得一個函式。
我有多個資料框:看起來都像
A <- data.frame(Date = as.character(c("Jan-22", "Dec-21", "Nov-21", "Oct-21")),
City1 = seq(1:4),
City2 = seq(1:8))
但有些資料框有更多的城市(3 到 8 個)。我想為所有資料框運行以下代碼:
Dates_A <- A$Date
A$Date <- NULL
nm1 <- combn(names(A), 2, FUN = paste, collapse = "_")
A[nm1] <- combn(A, 2, FUN = function(x) abs(x[[1]]- x[[2]]))
Casava$A<- Dates_A
它適用于我的第一個資料框。所以我試圖把我所有的資料框放到一個串列中
dfList <- list(A, B, C, D, E)
并將代碼放入回圈中:
for (i in 1: length(dfList))
{
Dates_i <- dfList[i]$Date
dfList[i]$Date <- NULL
nm1 <- combn(names(dfList[[i]]), 2, FUN = paste, collapse = "_")
dfList[i][nm1] <- combn(dfList[[i]], 2, FUN = function(x) abs(x[[1]]- x[[2]]))
dfList[i] <- select(dfList[[i]], contains("_"))
dfList[i]$Dates <- Dates_i}
但現在我得到錯誤:
x[[1]] - x[[2]] 中的錯誤:二元運算子的非數字引數
有人可以幫忙嗎?我不熟悉回圈。
編輯:對不起,我更正了我在單個 Dataframe 上運行的第一個代碼(3 我只是因為我嘗試過它 - 我現在不起作用,2 是我想要的)。
我的代碼僅在該點的回圈內中斷
dfList[i][nm1] <- combn(dfList[[i]], 2, FUN = function(x) abs(x[[1]]- x[[2]]))
uj5u.com熱心網友回復:
我會做的略有不同。我會將所有內容包裝在一個函式中并應用,即
f1 <- function(df){
cbind.data.frame(df,
lapply(combn(df[-1], 2, simplify = FALSE), function(i) {
nm <- paste0(names(i[1]), '_', names(i[2]));
i[nm] <- i[1] - i[2];
i[3]}))
}
> f1(A)
Date City1 City2 City3 City1_City2 City1_City3 City2_City3
1 Jan-22 1 1 1 0 0 0
2 Dec-21 2 2 2 0 0 0
3 Nov-21 3 3 3 0 0 0
4 Oct-21 4 4 4 0 0 0
5 Jan-22 1 5 5 -4 -4 0
6 Dec-21 2 6 6 -4 -4 0
7 Nov-21 3 7 7 -4 -4 0
8 Oct-21 4 8 8 -4 -4 0
9 Jan-22 1 1 9 0 -8 -8
10 Dec-21 2 2 10 0 -8 -8
11 Nov-21 3 3 11 0 -8 -8
12 Oct-21 4 4 12 0 -8 -8
13 Jan-22 1 5 13 -4 -12 -8
14 Dec-21 2 6 14 -4 -12 -8
15 Nov-21 3 7 15 -4 -12 -8
16 Oct-21 4 8 16 -4 -12 -8
然后將該功能應用于您的串列,即
lapply(dfList, f1)
資料
structure(list(Date = c("Jan-22", "Dec-21", "Nov-21", "Oct-21",
"Jan-22", "Dec-21", "Nov-21", "Oct-21", "Jan-22", "Dec-21", "Nov-21",
"Oct-21", "Jan-22", "Dec-21", "Nov-21", "Oct-21"), City1 = c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L),
City2 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L), City3 = 1:16), class = "data.frame", row.names = c(NA,
-16L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477844.html
上一篇:Pandas-添加新列-使用回圈
下一篇:根據索引組合串列
