Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace (recode) values in a list

Tags:

r

A have a list that has the following structure.

mylist=list(y~ A,
y ~ A+B,
y ~ A+B+C)

I want to replace (recode) the “y “ with a “z”. my goal is

mylist=list(z~ A,
z ~ A+B,
z ~ A+B+C)

Q: How to replace (recode) values in a list?

I have tried this:

for i in range(len(mylist)):
  mylist[i] = mylist[i].replace('y','z')

is not working

like image 890
Adam Avatar asked Nov 28 '22 13:11

Adam


2 Answers

The update function is useful for formulas.

Just include a . to indicate any formula side to retain. So, for your problem the following is a quick one-liner.

lapply(mylist, update, new = z~.)

like image 173
NJBurgo Avatar answered Dec 05 '22 13:12

NJBurgo


I would alternatively suggest to use R built in formulas manipulation functionality. This allows us to operate on different terms of a fromula separately without using regex

lapply(mylist, function(x) reformulate(as.character(terms(x))[3], "z"))
# [[1]]
# z ~ A
# <environment: 0x59c6040>
#   
# [[2]]
# z ~ A + B
# <environment: 0x59c0308>
#   
# [[3]]
# z ~ A + B + C
# <environment: 0x59bb7b8>
like image 37
David Arenburg Avatar answered Dec 05 '22 13:12

David Arenburg