从索引列替换数据框中的先前实例

时间:2019-10-07 18:46:20

标签: r

嗨,我有一个类似的问题 [文字](Replace values in data frame from column of indexes) 我有一个数据框架,如下所示。

Select * from
  (Select t.*, 
  Row_number() over 
  (partition by t.employee_id, t.asg_number order by t.effective_start_date desc) as rn
  From asg_table t
  Where t.location is null 
  AND t.action_code = 'HIRE')
Where rn = 1;

其中“索引”告诉我某个阈值。对于每一行,我想用唯一值(例如99)替换所有列值(直到“ index”所指示的值)。因此,我最终会得到类似

的内容
COL1 <- c(1,1,1,NA,1,1)
COL2 <- c(1,NA,NA,1,1,1)
COL3 <- c(1,1,1,1,1,1)
index <- c(2,3,2,3,2,2)
Data <- data.frame (COL1, COL2, COL3, index)
Data
COL1 COL2 COL3 index
1    1    1    2
1    NA   1    3
1    NA   1    2
NA   1    1    3
1    1    1    2
1    1    1    2

从上一个问题开始,在“索引”之后更改实例的答案将是

COL1 COL2 COL3
99   99   1
99   99   99
99   99   1
99   99   99
99   99   1
99   99   1

但这会引发我错误

  

“如果(i1!= 0)i1:3 else i1错误:     缺少需要TRUE / FALSE的值”

2 个答案:

答案 0 :(得分:3)

Heere是apply的一个选项,其中我们遍历各行(MARGIN = 1),replace通过基于第4个value列创建条件并分配每行的值到99

t( apply(Data, 1, function(x) replace(x, seq_along(x) <= x[4], 99)))[,-4]
#     COL1 COL2 COL3
#[1,]   99   99    1
#[2,]   99   99   99
#[3,]   99   99    1
#[4,]   99   99   99
#[5,]   99   99    1
#[6,]   99   99    1

或者采用向量化方法,通过基于col索引和'Data'的'index'列创建逻辑矩阵,以replace的前3列值为99

replace(Data[1:3], col(Data[1:3]) <= Data$index, 99)
#  COL1 COL2 COL3
#1   99   99    1
#2   99   99   99
#3   99   99    1
#4   99   99   99
#5   99   99    1
#6   99   99    1

答案 1 :(得分:2)

.cpu cortex-a53
.fpu neon-fp-armv8

.data

string: .asciz "Enter a Fibonacci term: "
scan: .asciz "%d"
result: .asciz "The %dth Fibonacci number is: %d\n"

.text
.align 2
.global main
.type main, %function

main:

push {fp, lr} @pushes on to stack
add fp, sp, #4 @adds the bytes to the stack

ldr r0, =string @loads string prompt into r0
bl printf @prints the string
sub sp, sp, #4 @allocates memory for sp
ldr r0, =scan @loads scan into r0
mov r1, sp @sp is moved to r1
bl scanf @branches to scanf

add sp, sp, #4 @creates bytes on stack

forloop:

cmp r0, #0 @compares user input to 0
bgt myexit @closes program if input is 0
mov r2, #0 @stores first term of fib
mov r3, #1 @stores second term of fib
add r2, r2, r3 @adds r2 & r3 then overwrites r2
bl forloop

ldr r6, =result
bl printf