【发布时间】:2021-01-04 23:23:37
【问题描述】:
您好,我有一个包含多个列的 DF,所有列都包含数值。我的 df 包含超过 200 列,但示例应该可以。我想从索引列表中获取值并在 RowSums 循环中使用它们,以便列表名称是新列,总和是索引的组合
Main <- c(rep(1, times = 6), rep(2, times = 6))
Feature1 <- sample(1:20, 12, replace = T)
Feature2 <- sample(400:500, 12, replace = T)
Feature3 <- sample(1:5, 12, replace = T)
df.main <- data.frame(Main, Feature1, Feature2,
Feature3, stringsAsFactors = FALSE)
Main Feature1 Feature2 Feature3
1 1 6 483 3
2 1 9 405 1
3 1 18 494 5
4 1 7 499 5
5 1 13 436 1
6 1 2 451 3
7 2 4 456 3
8 2 19 442 5
9 2 16 437 2
10 2 4 497 4
11 2 7 497 3
12 2 5 466 1
list(`Cool Ranch|Cool Chipotle` = c(1L, 4L,), `Trust|Scotia` = c(3L,
4L))
我希望我的输出看起来像这样
Main Feature1 Feature2 Feature3 cool_ranch trust_scotia
1 1 6 483 3 4 486
2 1 9 405 1 2 406
3 1 18 494 5 6 499
4 1 7 499 5 6 504
5 1 13 436 1 2 437
6 1 2 451 3 4 454
7 2 4 456 3 5 459
8 2 19 442 5 7 447
9 2 16 437 2 4 439
10 2 4 497 4 6 501
11 2 7 497 3 5 500
12 2 5 466 1 3 467
我已经尝试了一些与下面相同的方法
> sum.test<- apply(df.main, 2, function(i) rowSums[vlist.imps$i])
Error in rowSums[vlist.imps$i] :
object of type 'closure' is not subsettable
【问题讨论】:
-
您的预期输出值是否正确。也许你需要
df.main[names(vlist.imps)] <- lapply(vlist.imps, function(x) rowSums(df.main[x])) -
@akrun 这似乎是我想要做的,谢谢!明天我会检查这些值,因为在这个大型数据集中有很多东西需要检查才能确定。谢谢!