【问题标题】:R replace nested lists' values by the values from another tableR用另一个表中的值替换嵌套列表的值
【发布时间】:2021-10-11 06:54:03
【问题描述】:

我有一个这样的嵌套列表表:

library(dplyr)
data <- data.frame(id = c(123,124,125,126)) %>%
  mutate(a = list(c("orange", "apple"), c("banana", "melon"), c("kiwi", "melon"), c("apple", "banana")),
         b = list(c("kiwi", "apple"), c("melon", "apple"), c("orange", "melon"), c("apple", "orange")))

我想将 ab 中的所有值替换为 new_values 中的对应值:

new_values <- data.frame(fruits = c("orange", "apple", "banana", "kiwi", "melon")) %>% 
  mutate(param = list(c(1,2,3), c(2,3,4), c(4,3,1), c(1,4,2), c(3,4,1)))

【问题讨论】:

  • 所以c("orange", "apple") 会变成list(c(1,2,3), c(2,3,4))?!

标签: r list replace


【解决方案1】:

您可以使用嵌套的lapply -

data[-1] <- lapply(data[-1], function(y) {
  lapply(y, function(x) new_values$param[match(x, new_values$fruits)])  
})

或者在tidyverse -

library(dplyr)
library(purrr)

data %>% mutate(across(a:b, function(x) 
         map(x, ~new_values$param[match(.x, new_values$fruits)])))

输出是一个嵌套列表 -

data$a

#[[1]]
#[[1]][[1]]
#[1] 1 2 3

#[[1]][[2]]
#[1] 2 3 4


#[[2]]
#[[2]][[1]]
#[1] 4 3 1

#[[2]][[2]]
#[1] 3 4 1
#...
#...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2021-10-08
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2022-11-12
    • 2019-04-10
    相关资源
    最近更新 更多