繁体   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