data.table将输出分配给变量列

问题描述 投票:1回答:2

因此,我要实现一个循环,如果该值(在a行和col b行)等于某个数字,则分配原始值(在a行和col b行)+1。使用with = FALSE分配数字,我无法这样做,将其删除会产生一个输出,其中整个col为=为原始值(在a行和col b行)+1。

测试用例:

a <- rep(0,6)
b <- 1:6
c <- -3:2
d <- runif(6)
e <-runif(6)
dt1 <- data.table("ID" = b,"code_a" = a,"code_c" = c, "code_d" = d, "code_e" = e)
dt1
   ID code_a code_c    code_d      code_e
1:  1      0     -3 0.5369538 0.269854945
2:  2      0     -2 0.7186787 0.009384648
3:  3      0     -1 0.8053726 0.831286263
4:  4      0      0 0.2084106 0.171294349
5:  5      0      1 0.0130021 0.730679582
6:  6      0      2 0.2902858 0.062175009

因此,在下文中,我分配了ctr <- 1并测试了我想用数字1替换col_2row_1的方案,但不幸的是,这两种方案都不是我想要的输出。

我的尝试次数1:

dt1[,eval(ctr+1), with = FALSE][ctr] <- 1

Error in `[<-.data.table`(`*tmp*`, , eval(ctr + 1), with = FALSE, value = list( : 
  unused argument (with = FALSE)

我的尝试次数2:

dt1[,eval(ctr+1)][ctr] <- 1
> dt1
   ID code_a code_c    code_d      code_e
1:  1      1     -3 0.5369538 0.269854945
2:  2      1     -2 0.7186787 0.009384648
3:  3      1     -1 0.8053726 0.831286263
4:  4      1      0 0.2084106 0.171294349
5:  5      1      1 0.0130021 0.730679582
6:  6      1      2 0.2902858 0.062175009

所需的输出:

   ID code_a code_c    code_d      code_e
1:  1      1     -3 0.5369538 0.269854945
2:  2      0     -2 0.7186787 0.009384648
3:  3      0     -1 0.8053726 0.831286263
4:  4      0      0 0.2084106 0.171294349
5:  5      0      1 0.0130021 0.730679582
6:  6      0      2 0.2902858 0.062175009

这可能是以前问过的,但是我找不到正确的方法来找到问这个问题的线程。我也尝试使用..ctr,但没有成功。如果有人可以帮助我了解发生了什么,将不胜感激。

r data.table
2个回答
1
投票

我们可以将setij索引一起使用

set(dt1, i = as.integer(ctr), j = 2L, value = 1)
dt1
#   ID code_a code_c     code_d     code_e
#1:  1      1     -3 0.37168485 0.89323758
#2:  2      0     -2 0.44402352 0.70270947
#3:  3      0     -1 0.50800021 0.82133031
#4:  4      0      0 0.14904232 0.33997461
#5:  5      0      1 0.03376199 0.22633368
#6:  6      0      2 0.42361025 0.02377616

0
投票

没关系,我忘了我不应该在data.frame中实际编写代码:

dt1[,eval(ctr+1), with = FALSE][ctr] <- 1

由于不必要,我不应该在这里链接,而只需使用data.frame表示法和:

dt1[eval(ctr),eval(ctr+1)] <- 1

这给了我

   ID code_a code_c    code_d      code_e
1:  1      1     -3 0.5369538 0.269854945
2:  2      0     -2 0.7186787 0.009384648
3:  3      0     -1 0.8053726 0.831286263
4:  4      0      0 0.2084106 0.171294349
5:  5      0      1 0.0130021 0.730679582
6:  6      0      2 0.2902858 0.062175009
© www.soinside.com 2019 - 2024. All rights reserved.