簡體   English   中英

在列表的數據框中設置一列等於 R 列表中的 dataframe 的名稱

[英]Set a column in dataframes of a list equal to the name of the dataframe in the list in R

我有一個 dataframe 的列表,例如:

my_list <- list(`1` = data.frame(x = c(1,2,3), y = c(3,3,3)),
                `2` = data.frame(x = c(4,8,1), y = c(4,4,4)),
                `3` = data.frame(x = c(5,7,6), y = c(8,8,8)))
print(my_list)

$`1`
  x y
1 1 3
2 2 3
3 3 3

$`2`
  x y
1 4 4
2 8 4
3 1 4

$`3`
  x y
1 5 8
2 7 8
3 6 8

我想寫一個 function 將列表my_list中數據幀中的y列設置為相應的names(my_list) 所需的 output 將是

$`1`
  x y
1 1 1
2 2 1
3 3 1

$`2`
  x y
1 4 2
2 8 2
3 1 2

$`3`
  x y
1 5 3
2 7 3
3 6 3

如果您熟悉 for 循環,只需在 function 中包裹一個 for 循環。

# build your function
# input your data list, loop through each of dataframe
# do what you need, then save the output

your_function <- function(data_list){
  for (i in 1:length(data_list)){
  data_list[[i]]$y <- names(data_list)[[i]]
  }
  return(data_list)
}

# now run your function
output <- your_function(my_list)

# check outputs
print(output)

你可以這樣做:

library(tidyverse)
imap(my_list, ~mutate(.x, y = .y))

在基礎 R 中,您可以執行以下操作:

Map(transform, my_list, y = names(my_list))
$`1`
  x y
1 1 1
2 2 1
3 3 1

$`2`
  x y
1 4 2
2 8 2
3 1 2

$`3`
  x y
1 5 3
2 7 3
3 6 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM