Replace (recode) the values ​​in the list

A have a list that has the following structure.

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

I want to replace (transcode) "y "with "z". my goal

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

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

I tried this:

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

does not work

+4
source share
4 answers

The function updateis useful for formulas.

Just turn .it on to indicate either side of the formula to save. So, for your problem, the next one-line fast.

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

+13
source

As an alternative, I would suggest using R built into the formula manipulation functionality. This allows us to work on different terms of aulula 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>
+6

, , gsub, . env, , , :

lapply(mylist, function(f) formula(gsub("y", "z", format(f)), env = .GlobalEnv))
# [[1]]
# z ~ A

# [[2]]
# z ~ A + B

# [[3]]
# z ~ A + B + C

@David Arenburg, y , :

lapply(mylist, function(f) formula(gsub("y(\\s)?(?=~)", "z", format(f), perl = T), env = .GlobalEnv))

# [[1]]
# z ~ A

# [[2]]
# z ~ A + B

# [[3]]
# z ~ A + B + C
+2

, . , [[<- . y , ~ , , .

lapply(mylist, "[[<-", 2, as.name("z"))
# [[1]]
# z ~ A
#
# [[2]]
# z ~ A + B
#
# [[3]]
# z ~ A + B + C
+2

Source: https://habr.com/ru/post/1649033/


All Articles