Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace specific values of all elements in a list

Tags:

list

r

lapply

I have a list cluster_list of 11 elements, each element of the same length.

 > class(cluster_list)
[1] "list"

Each element looks like the example element 2:

head(cluster_list[[2]][,1:15])
     X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15
765   t  t  t  c  t  t  a  a  a   a   c   a   t   a   a
7319  -  -  -  -  -  -  -  -  -   -   -   -   -   -   -
8335  t  t  t  c  t  t  a  a  a   a   c   a   t   a   a
7162  -  -  -  -  -  -  -  -  -   -   -   t   c   t   a
7382  -  -  -  -  -  -  -  -  -   -   -   -   -   -   -
7244  -  -  -  -  -  -  -  -  -   -   -   -   -   -   -

I want to remove/change all "-" to "" for all 11 elements in the list

I know how to do it in a matrix:

matrix_new <- matrix_old[matrix_old=="-"] <- ""

Or how to remove a column of a element in a list:

cluster_list <- lapply(cluster_list, function(x) x[!(names(x) %in% c("X1"))])

But I´m unable to remove "-" from the list. (I´m new to using list and the lapply function) Any suggestions to make it look like:

> head(cluster_list[[2]][,1:15])
     X1  X2  X3  X4  X5  X6  X7  X8  X9  X10 X11 X12 X13 X14 X15
765  "t" "t" "t" "c" "t" "t" "a" "a" "a" "a" "c" "a" "t" "a" "a"
7319 ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  "" 
8335 "t" "t" "t" "c" "t" "t" "a" "a" "a" "a" "c" "a" "t" "a" "a"
7162 ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  "t" "c" "t" "a"
7382 ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  "" 
7244 ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  ""  "" 

thx K

like image 395
Konrad Weber Avatar asked Dec 07 '25 06:12

Konrad Weber


1 Answers

We can loop through the list, and use replace, to change the values that are - to blank ('')

cluster_list_new <- lapply(cluster_list, function(x) replace(x, x== '-', ''))
like image 69
akrun Avatar answered Dec 09 '25 21:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!