【问题标题】:R Using an array to subset a tableR使用数组对表进行子集化
【发布时间】:2015-06-29 11:33:44
【问题描述】:

我刚刚使用 assign 函数在循环中创建了 10 个变量:

#Original.data.frame is a 10X5 data frame.
#table is a table of the combinations of Col.nums where r=2
Col.nums<- c(1:5)
 for(i in 1:ncol(data.frame)){
  name<- paste("Name.object.",i, sep = "")
  Boolean<- Col.nums %in% table[,i]
  assign(name,expand.grid(Original.data.frame[Boolean]))      
}

我现在想添加创建另一个对象 (Name.object.total.i),其中 i 是每次迭代。

我的问题是:有没有一种方法可以在每次迭代中对名称进行索引以便能够在其上运行 rowSums 函数?


编辑: 基本上我想补充:

name$row.sums<- rowSum(name[1:2])

到该循环的末尾,但将 name 替换为 name 的内容(在循环的第一行中定义)。

为了形象化,上面的循环产生了 10 个对象,每个对象都是 10x5 数据框的子集的组合。一个示例子集:

           Cost.1             Cost.2
1          9104.014           26118.75
2         10901.258           26118.75
3         11952.579           26118.75
4         12698.503           26118.75
5         13277.086           26118.75
6         13749.823           26118.75
7         14149.517           26118.75

我期望的输出是上面的 10 个表,其中有一列是前两行的总和。希望这能让它更清楚!

【问题讨论】:

  • 其实我在重读你的帖子时删除了我的帖子。我不知道你想要什么,但这不是我最初的想法。最好发布一些示例数据以及您期望的输出。
  • 再试一次。仍然不确定我是否理解任务。
  • 我设法找到了一种不同的方法来获得我的结果。很抱歉没有很好地解释它,即使对我来说也很困惑。我确实了解了 sprintf,它可能会在其他地方派上用场。干杯!
  • 好吧,我的帖子是否回答了您的问题?我为此投入了工作。如果是这样,您应该将其标记为答案。如果不是,你应该解释为什么会这样。如果你想删除它,你应该删除你的帖子。

标签: r loops


【解决方案1】:

这是你要找的吗?

df <- data.frame(runif(10),runif(10),runif(10),runif(10),runif(10))
names(df) <- sprintf("Col.%d",1:ncol(df))

colnums1 <- 1:3
colnums2 <- 4:5

df$cost.1 <- rowSums(df[,colnums1])
df$cost.2 <- rowSums(df[,colnums2])

产生这个:

> df
        Col.1     Col.2     Col.3     Col.4     Col.5    cost.1    cost.2
1  0.02554691 0.0348292 0.2318146 0.1358425 0.9466410 0.2921907 1.0824835
2  0.58132588 0.7876859 0.7916831 0.7257976 0.6240524 2.1606948 1.3498500
3  0.29918389 0.7582891 0.9910775 0.1924936 0.5182367 2.0485505 0.7107303
4  0.74494794 0.8174732 0.3195831 0.7058671 0.4047919 1.8820042 1.1106590
5  0.52303788 0.1036358 0.8388999 0.8052366 0.1312974 1.4655735 0.9365340
6  0.20339176 0.5381387 0.4736697 0.1199182 0.7620207 1.2152002 0.8819390
7  0.42020501 0.3035775 0.3269214 0.1702709 0.5577061 1.0507039 0.7279769
8  0.27012667 0.8610641 0.8194125 0.3870223 0.2208947 1.9506033 0.6079170
9  0.04770033 0.8950735 0.1927350 0.8565112 0.4924964 1.1355088 1.3490075
10 0.99183198 0.8061123 0.5915283 0.9464604 0.8511332 2.3894725 1.7975936
> 

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多