我目前已创建了许多数据子集,我将其命名为A.sub,B.sub,C.sub等。我想使用循环尝试为每个子集添加一个列在data.frame中的列名称上。对于具有列名A,B,C的帧,我希望能够调用[列名] .sub(例如A.sub,B.sub,C.sub)。我试图从中绘制列名称的data.frame的名称称为SellList。我目前的尝试看起来像这样(数据简化以显示我尝试做的更明确的例子):
<hr style="margin: 10px">
<div><p>Matching Text</p></div>
最终目标是让潜艇看起来像:
> SellList
A B C
Sale Amount 30000 20000 10000
> A.sub
Price Holdings $ Amt Owned
101.4 400 40560
> B.sub
Price Holdings $ Amt Owned
95.5 300 28650
> C.sub
Price Holdings $ Amt Owned
154.1 100 15450
for(i in 1:width(SellList)){
colnames(SellList[i]).sub$SaleAmount <- SellList[1,i]
}
我尝试过的另一种似乎无法正常工作的方法是将所有子集放入列表中,然后像这样运行列表:
> A.sub
Price Holdings $AmtOwned SaleAmount
101.4 400 40560 30000
> B.sub
Price Holdings $AmtOwned SaleAmount
95.5 300 28650 20000
> C.sub
Price Holdings $AmtOwned SaleAmount
154.1 100 15450 10000
答案 0 :(得分:1)
如果将子集放入列表中,这可能是包 purrr 中map2
的作业。 map2
函数是指具有两个相同长度的单独列表的函数。我将子集列为sublist
。
sublist
$A.sub
Price Holdings $ Amt Owned
1 101.4 400 40560
$B.sub
Price Holdings $ Amt Owned
1 95.5 300 28650
$C.sub
Price Holdings $ Amt Owned
1 154.1 100 15450
现在,您可以使用map2
循环浏览sublist
和SellList
并将它们合并。由于您的所有变量都是数字,因此我使用了cbind
,但如果您使用了混合类型,则可以将data.frame
与check.names = FALSE
一起使用。
library(purrr)
map2(sublist, SellList, ~cbind(.x, SaleAmount = .y))
$A.sub
Price Holdings $ Amt Owned SaleAmount
1 101.4 400 40560 30000
$B.sub
Price Holdings $ Amt Owned SaleAmount
1 95.5 300 28650 20000
$C.sub
Price Holdings $ Amt Owned SaleAmount
1 154.1 100 15450 10000
我使用代字号编码命名新列SaleAmount
,其中.x.
表示第一个列表,.y
表示第二个列表。
另一种替代方法是使用map2_df
将子集绑定到单个data.frame中。使用.id
参数添加一列来标识子集。
map2_df(sublist, SellList, ~cbind(.x, SaleAmount = .y), .id = "Sub")
Sub Price Holdings $ Amt Owned SaleAmount
1 A.sub 101.4 400 40560 30000
2 B.sub 95.5 300 28650 20000
3 C.sub 154.1 100 15450 10000
答案 1 :(得分:0)
以下是我在基础R中解决这个问题的方法:
# put .sub objects into a list
myList <- mget(ls(pattern="\\.sub$"))
# add on extra variable using lapply
myList <- lapply(seq_along(myList),
function(i) c(myList[[i]], "SaleAmount"=sellList[[i]][1L]))
这将返回一个嵌套列表,其中外部嵌套的名称为A.sub,B.sub,C.sub,内部列表应如您的示例所示。请注意,这要求对象按照示例中的名称进行命名和组织。
答案 2 :(得分:-2)
for(i in 1:length(names(SellList))){
eval(parse(text = paste0(colnames(SellList)[i], ".sub$SaleAmount <- SellList[1,", i, "]"))
}
我只测试了i = 1
A.sub
Price Holdings AmtOwned SaleAmount
1 101.4 400 40560 30000