[英]r: lapply but with dynamic naming
假設我在一個列表中有 5 個數據集(每個名為df_1
、 df_2
等),每個數據集都有一個名為cons
的變量。 我想對列表中每個數據集中的cons
執行一個函數,並創建一個新變量,其名稱具有相應數據集的后綴。
那么到底df_1
將有一個變量,名為像cons_1
和df_2
會有一個叫做可變cons_2
。 我遇到的問題是變量循環並嘗試創建動態名稱。
有什么建議?
這實際上非常簡單:
df_names <- paste("df", 1:5, sep = "_")
cons_names <- paste("cons", 1:5, sep = "_")
for (i in 1:5) {
# get the df from the current env by name
df_i <- get(df_names[i])
# do whatever you need to do and assign the result
df_i[[cons_names[i]]] <- some_operation(df_i)
}
但是將數據框保存在列表中以避免使用get
會更有意義,這可能是粗略的:
for (i in 1:5) {
df_i[[cons_names[i]]] <- some_operation(df_list[[i]])
}
使用 purrr 包,這將是一個替代解決方案:
library(purrr)
lst <- list(mtcars_1 = mtcars,
mtcars_2 = mtcars,
mtcars_3 = mtcars,
mtcars_4 = mtcars,
mtcars_5 = mtcars)
map(seq_along(lst), function(x) {
lst[[x]][paste0("mpg_", x)] <- some_operation(lst[[x]]['mpg']); lst[[x]]
})
從列表中子集每個數據幀,使用當前數據幀的索引創建新的 mpg 變量,並對 mpg 變量執行您想要的任何操作。 結果是一個列表,其中包含以前數據幀的所有數據以及每個數據幀的新變量。
由於這個新列表沒有數據框名稱,您可以隨時使用setNames(newlist, names(lst))
添加它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.