我的输入和相关输出会在以后发生。有时1输入可能会产生多个输出。我想将输入和第一个输出与此输入相关联在同一行(在输入的时刻)。因此,我必须从输入时间的行开始找到第一个非空的单元格。
这是我的数据集:
time event result_of event
11:15 input1
11:16
11:17
11:18 output1
11:19
11:20 output2
11:21 input2
11:22 output3
11:23
11:24 input3
11:25
11:26 output4
11:27 input4
11:28
11:29 output5
这是我期望的结果:
time event result_of event
11:15 input1 output1
11:16
11:17
11:18
11:19
11:20
11:21 input2 output3
11:22
11:23
11:24 input3 output4
11:25
11:26
11:27 input4 output5
11:28
11:29
代码应该是灵活的,因为输入和输出之间可能有很多行,所以它应该始终检查从当前行开始直到最后一行的非空单元格。
事先感谢你!
答案 0 :(得分:0)
# get the data
lines = readLines("file.txt")
# get the input and output line numbers
inputs = grep(".{8}i", lines)
outputs = grep(".{12}o", lines)
# find the first output after each input
n_inputs = length(inputs)
outputs1 = vector(length = n_inputs)
for (x in 1:n_inputs) {
outputs1[x] = outputs[which(outputs > inputs[x])[1]]
}
# rearrange the data
outputs_text = substr(lines[outputs1], 13, 19)
lines[inputs] = paste0(lines[inputs], outputs_text)
lines[-inputs] = substr(lines[-inputs], 1, 5)
lines[1] = "time event result_of event"
writeLines(lines, "newfile.text")