Home > OS >  Replacing a list value with a string
Replacing a list value with a string

Time:05-08

I have data as follows:

dat <- list(c(0, 25, 100, 250, 500, 1000, 1e 06))

I am simply trying to replace the value 1000000 with the string value "Infinity". Even though:

dat[1]
# [[1]]
# [1]       0      25     100     250     500    1000 1000000

dat[[1]

# [1]       0      25     100     250     500    1000 1000000

If I try:

gsub(1000000, "Infinity", dat[[1]])

Nothing happens. Why does nothing happen in this case and what would be the right way to do this?

CodePudding user response:

You need to assign the RHS gsub call to a LHS variable, probably the vector itself inside the list. But, given that your initial vector contains numerical values, you should instead use equality here:

dat[[1]][dat[[1]] == 1000000] <- "Infinity"
dat

[[1]]
[1] "0" "25" "100" "250" "500" "1000" "Infinity"

CodePudding user response:

We could use rapply. rapply is a recursive version of lapply with flexibility in how the result is structured (how = ".."). See ?rapply

rapply(dat,function(x) ifelse(x==1000000,"Infinity",x), how = "replace")
[[1]]
[1] "0"        "25"       "100"      "250"      "500"      "1000"     "Infinity"

CodePudding user response:

If you really want to use gsub, you need to set fixed = TRUE.

dat <- list(c(0, 25, 100, 250, 500, 1000, 1e 06))

dat[[1]] <- gsub(1000000, "Infinity", dat[[1]], fixed = T)

dat
[[1]]
[1] "0"        "25"       "100"      "250"      "500"      "1000"    
[7] "Infinity"

CodePudding user response:

Another option using replace and lapply (though rapply is the better choice over lapply):

lapply(dat, function(x) replace(x, x == 1000000, "Infinity"))

Output

[[1]]
[1] "0"        "25"       "100"      "250"      "500"      "1000"     "Infinity"
  • Related