Konrad Weber
Konrad Weber

Reputation: 157

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

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

Upvotes: 3

Views: 205

Answers (1)

akrun
akrun

Reputation: 887048

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== '-', ''))

Upvotes: 4

Related Questions