Suppose i have many and larger lists than in this example.
ID <- c(2,2,2,2,5,5,5,5,9,9,9,9)
Rounds <- c(0,1,2,3,0,1,2,3,0,1,2,3)
solution <- c(as.character('[[-1,1,1,-1],[1,-1,1,-1]]'),as.character('[[-1,1,-1,-1],[1,-1,1,-1]]'),as.character('[[-1,1,1,-1],[1,-1,-1,-1]]') )
solution_resp <- c(as.character('[[-1,1,1,1],[1,1,-1,1]]'),as.character('[[1,-1,1,-1],[1,-1,1,1]]'),as.character('[[-1,1,1,1],[1,-1,1,-1]]'))
dt <- data.frame(ID,Rounds,solution,solution_resp)
dt$solution <- gsub('],[',',', dt$solution, fixed=TRUE)
dt$solution <- gsub('[[','' , dt$solution, fixed=TRUE)
dt$solution <- gsub(']]','' , dt$solution, fixed=TRUE)
dt$solution <- as.list(strsplit(dt$solution, ","))
dt$solution_resp <- gsub('],[',',', dt$solution_resp, fixed=TRUE)
dt$solution_resp <- gsub('[[','' , dt$solution_resp, fixed=TRUE)
dt$solution_resp <- gsub(']]','' , dt$solution_resp, fixed=TRUE)
dt$solution_resp <- as.list(strsplit(dt$solution_resp, ","))
Looks like this:
ID Rounds solution solution_resp
1 2 0 -1, 1, 1, -1, 1, -1, 1, -1 -1, 1, 1, 1, 1, 1, -1, 1
2 2 1 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
3 2 2 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
4 2 3 -1, 1, 1, -1, 1, -1, 1, -1 -1, 1, 1, 1, 1, 1, -1, 1
5 5 0 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
6 5 1 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
7 5 2 -1, 1, 1, -1, 1, -1, 1, -1 -1, 1, 1, 1, 1, 1, -1, 1
8 5 3 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
9 9 0 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
10 9 1 -1, 1, 1, -1, 1, -1, 1, -1 -1, 1, 1, 1, 1, 1, -1, 1
11 9 2 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
12 9 3 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
In the lists dt$solution_resp I would like to drop all 1 from behind until the first -1 appears (counting from right to left).
In the example this would mean shortening the lists by taking off the last element in first row (and every third row). In the second row (and every third) the list shall be shorted by two elements. The third row remains as it is because there is a -1 at the last position already.
Then, I want the dt$solution lists to have the same length.
Solution:
ID Rounds solution solution_resp
1 2 0 -1, 1, 1, -1, 1, -1, 1 -1, 1, 1, 1, 1, 1, -1
2 2 1 -1, 1, -1, -1, 1, -1 1, -1, 1, -1, 1, -1
3 2 2 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
4 2 3 -1, 1, 1, -1, 1, -1, 1 -1, 1, 1, 1, 1, 1, -1
5 5 0 -1, 1, -1, -1, 1, -1 1, -1, 1, -1, 1, -1
6 5 1 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
7 5 2 -1, 1, 1, -1, 1, -1, 1 -1, 1, 1, 1, 1, 1, -1
8 5 3 -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1
9 9 0 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
10 9 1 -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1
11 9 2 -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1
12 9 3 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1