I have a data file whose minimum reproducible example is this .
The file contains a named variable Population_signals
whose fields contain data grouped as vectors with square brackets (eg [1,0,0,0,0,0,0,0,0,9])
I would like to know if there is any function in R that allows to invert the order of the indices of vectors, in such a way that for example, if a vector is [1,0,0,0,0,0,0,0,0, 9] the function would return [9,0,0,0,0,0,0,0,0,1].
The algorithm I would like to use to change the order of the vectors of the odd rows of a dataframe. The desired result with the shared dataframe would be as follows:
1 Population_signals
2 [0, 0, 0, 0, 0, 0, 0, 0, 0, 10]
3 [8, 0, 0, 0, 0, 0, 0, 0, 0, 2]
4 [0, 0, 2, 0, 0, 0, 0, 0, 8, 0]
5 [0, 10, 0, 0, 0, 0, 0, 0, 0, 0]
6 [0, 0, 0, 0, 0, 0, 0, 10, 0, 0]
7 [0, 0, 7, 0, 0, 0, 0, 0, 3, 0]
The issue is that data is finally what you are looking for, now it is clearly a "character" column that must be interpreted as a vector to reverse the order:
With
gsub("\\[|\\]", '', df$Population_signals)
, we remove the brackets and withstrsplit()
, we separate the string by,
and generate a list of vectors, finally withlapply()
we applyrev(as.integer(x))
, that is, we convert the strings into integers and invert the order and we already have the data interpreted and reversed.If we then eventually want to generate a column similar to the original:
An alternative, similar to Patrick's but using tidyverse. Modifies only the odd rows of the data.frame.
Result: