替换列表中的值,同时保留原始形状/长度

时间:2018-01-07 08:57:00

标签: r list replace

我有一个值为t_blocks的列表,其长度为[1] 22,其中我需要替换所有每个实例,其值为“ord”。

[[1]]
[1] 3 4 5

[[2]]
[1] 6 7 8 9

[[3]]
[1] 10 11 12

[[4]]
[1] 13 14 15 16

[[5]]
[1] 17 18 19 20 21

[[6]]
[1] 22 23 24 25 26

[[7]]
[1] 27 28 29 30 31 32 33

[[8]]
[1] 34 35

[[9]]
[1] 36 37 38 39 40 41

[[10]]
[1] 42 43 44 45 46

[[11]]
[1] 47 48 49 50

[[12]]
[1] 51 52 53 54 55

[[13]]
[1] 56 57

[[14]]
[1] 58 59 60 61 62

[[15]]
[1] 63 64 65 66 67 68 69

[[16]]
[1] 70 71 72

[[17]]
[1] 73 74 75 76 77

[[18]]
[1] 78 79 80 81

[[19]]
[1] 82 83 84

[[20]]
[1] 85 86 87 88 89

[[21]]
[1] 90 91 92 93 94

[[22]]
[1] 2

我尝试了relistreplace

t_scaling = unlist(t_blocks)
relist(replace( t_scaling,  t_scaling>="0", "ord"), skeleton=t_blocks)

但这导致列表的长度为[1] 93。

在保留t_blocks列表的原始“形状”的同时,还有其他方法可以替换吗?

2 个答案:

答案 0 :(得分:2)

如果要创建新值列表,但长度相同,则可以执行此操作:

# Create data
foo <- list(1:5, 1:3, 1:2)
wantedValue <- "ord"
# Get lengths of vectors (i) and repeat wantedValue i times
lapply(lapply(foo, length), function(i) rep(wantedValue, i))

结果:

# [[1]]
# [1] "ord" "ord" "ord" "ord" "ord"
# 
# [[2]]
# [1] "ord" "ord" "ord"
# 
# [[3]]
# [1] "ord" "ord"

答案 1 :(得分:1)

一个使用purrr的解决方案和另一个使用基础R replace函数的解决方案

library(purrr)
ll <- list(
  c(3, 4, 5),
  c(6, 7, 8, 9),
  c(10, 11, 12)
) 

ll %>%
  map(~ replace(.x, .x > 0, "ord"))
#> [[1]]
#> [1] "ord" "ord" "ord"
#> 
#> [[2]]
#> [1] "ord" "ord" "ord" "ord"
#> 
#> [[3]]
#> [1] "ord" "ord" "ord"


lapply(ll, function(x) replace(x, x > 0, "ord"))
#> [[1]]
#> [1] "ord" "ord" "ord"
#> 
#> [[2]]
#> [1] "ord" "ord" "ord" "ord"
#> 
#> [[3]]
#> [1] "ord" "ord" "ord"