我有一長串資料框。我想獲取每個資料框名稱的最后兩個字串,并用它來替換串列中每個資料框特定列中的所有值。
玩具示例:
df_stringPA <- data.frame(name="MU",
col1= c(1,2,3),
col2= c(1,2,3))
df_stringCA <- data.frame(name="MU",
col1= c(1,2,3),
col2= c(1,2,3))
test_list <- list(PA=df_PA, CA=df_CA)
### desired output:
output_df_PA <- data.frame(name="PA",
col1= c(1,2,3),
col2= c(1,2,3))
output_df_CA <- data.frame(name="CA",
col1= c(1,2,3),
col2= c(1,2,3))
如果我為串列中的單個資料框執行此操作,它會起作用:
### doing it separately for each df within the list:
test_list$PA$name <- str_sub(deparse(substitute(test_list$PA)), start= -2)
但這是一個很長的串列,因此手動操作并不是最佳選擇。我已經測驗過:
test_list <- lapply(test_list, function(x) x$name <- str_sub(deparse(substitute(x)), start= -2))
但是我將串列中的資料框替換為 ']]'
uj5u.com熱心網友回復:
您可以使用Map:
Map(function(a, b) {a$name <- b; a}, a = test_list, b = names(test_list))
$PA
name col1 col2
1 PA 1 1
2 PA 2 2
3 PA 3 3
$CA
name col1 col2
1 CA 1 1
2 CA 2 2
3 CA 3 3
uj5u.com熱心網友回復:
我們可以使用imap
library(purrr)
library(dplyr)
imap(test_list, ~ .x %>%
mutate(name = .y))
$PA
name col1 col2
1 PA 1 1
2 PA 2 2
3 PA 3 3
$CA
name col1 col2
1 CA 1 1
2 CA 2 2
3 CA 3 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451051.html
下一篇:Prolog:將術語轉換為字串?
