So I have this kind of data:
a <- data.table("a"=c("1 42"," 84","2 10","3 12"," 24"))
a
1: 1 42
2: 84
3: 2 10
4: 3 12
5: 24
The data is a single sorted vector consisting of strings with IDs 1, 2 and 3 and data on the IDs.
For further processing I need to fill in the ID numbers in the missing places. The number of spaces between ID and the data, as well as the number of spaces before the data when there is no ID is fixed. In the example there are 4 spaces between ID and the data, and 5 spaces if there is no ID. The result should look like this:
a <- data.table("a"=c("1 42","1 84","2 10","3 12","3 24"))
a
1: 1 42
2: 1 84
3: 2 10
4: 3 12
5: 3 24
I have solved this in Excel
by copying the first cell A1
into B1
and using this formula in B2
: =IF(LEFT(A2,5)=" ",LEFT(B1,5)&A2,A2)
.
I am aware that this adds additional spaces, but that doesn't matter for the further processing of the data.
I am struggling to find a solution in R, but I found this and this on how to refer to a previous value in a data.table
. However, I'm stuck on how to use those commands to check the if-condition and paste
the strings together.