gpt4 book ai didi

r - 使用 purrr 更改每个列表(嵌套列表)的每个元素

转载 作者:行者123 更新时间:2023-12-03 21:10:29 25 4
gpt4 key购买 nike

我有数百个人口普查数据的观察 - 每个特征都存储在一个名为人口普查的列表中。我正在尝试执行操作
a) 在所有列表的所有元素上:我想将所有非字符元素设为数字。
b)每个列表中存在的命名元素:我想从每个列表的命名列中删除前缀
下面是一个玩具示例。
人口普查是列表中的嵌套列表

library(tidyverse)
library(purrr)


POA_CODE = c("POA101","POA102")
dogs = c(4,4)
cats = c(3,2)

children = c(0, 1)

salary = c(100, 120)
employed.prop = c(1,0.5)

pets <- list(POA_CODE, as.integer(dogs), as.integer(cats))

children <-list(POA_CODE, as.integer(children))

employment <-list(POA_CODE, salary, employed.prop)

census <- list(pets, children, employment)
尝试将每个列表中的所有非数字元素更改为数字
#change all non-numeric elements to numeric
census_num <- census %>%
map(function(x){
ifelse(is.character == TRUE, x,
as.numeric(x))}
)
我收到以下错误消息:
Error in is.character == TRUE : 
comparison (1) is possible only for atomic and list types
尝试从 census[[]]$'POA_CODE' 中的每个邮政编码中删除前缀
#Remove "POA" prefix from every postcode
census_code <- pmap(census, ~.x[["POA_CODE"]],function(x){
str_replace(POA_CODE,"POA","")
})
我收到错误
Error: Element 2 of `.l` must have length 1 or 3, not 2

最佳答案

您有一个嵌套列表,因此您需要嵌套 map :

library(purrr)
map(census, function(x) map_if(x, is.character, ~as.numeric(sub('POA', '', .x))))

#[[1]]
#[[1]][[1]]
#[1] 101 102

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

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


#[[2]]
#[[2]][[1]]
#[1] 101 102

#[[2]][[2]]
#[1] 0 1


#[[3]]
#[[3]][[1]]
#[1] 101 102

#[[3]][[2]]
#[1] 100 120

#[[3]][[3]]
#[1] 1.0 0.5
在基础 R 中,我们可以使用嵌套的 lapply 来解决它:
lapply(census, function(x) lapply(x, function(y) 
if(is.character(y)) as.numeric(sub('POA', '', y)) else y))

关于r - 使用 purrr 更改每个列表(嵌套列表)的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64097888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com