[英]Convert chararacter numbers to numeric in nested list with mixed types in R
I have a bunch of nested lists that arrive with all character-typed elements.我有一堆嵌套列表,其中包含所有字符类型的元素。 Some of these characters are in fact numbers that need to be converted to numeric-typed elements.
其中一些字符实际上是需要转换为数字类型元素的数字。
How can I modify these lists so that all possible character-typed numbers are converted to numeric, but the non-number character elements remain intact (eg, aren't converted to NA
by as.numeric()
)?如何修改这些列表,以便将所有可能的字符类型数字转换为数字,但非数字字符元素保持不变(例如,不通过
as.numeric()
转换为NA
)?
For example, I start with例如,我从
raw_list <- list(
'a' = list('1', '2'),
'b' = list(
'c' = list('3', 'x'),
'd' = c('4', 'z'),
'e' = '5'))
But I need to get to但我需要到达
cleaned_list <- list(
'a' = list(1, 2),
'b' = list(
'c' = list(3, 'x'),
'd' = c(4, 'z'),
'e' = 5))
Bonus: Extra gratitudie for tidyverse/purrr-based solutions奖励:额外感谢基于 tidyverse/purrr 的解决方案
Another option is to use type.convert
, which can take lists as arguments.另一种选择是使用
type.convert
,它可以将列表作为 arguments。
raw_list %>%
type.convert(as.is = TRUE)
This would be the same as using purrr
with type.convert
.这与使用
purrr
和type.convert
相同。
library(purrr)
purrr::map(raw_list, type.convert, as.is = TRUE)
Output Output
$a
$a[[1]]
[1] 1
$a[[2]]
[1] 2
$b
$b$c
$b$c[[1]]
[1] 3
$b$c[[2]]
[1] "x"
$b$d
[1] "4" "z"
$b$e
[1] 5
You can use readr::parse_guess
to convert character-typed numbers to numeric-typed numbers without converting characters to NA
s.您可以使用
readr::parse_guess
将字符类型的数字转换为数字类型的数字,而无需将字符转换为NA
。
I also created a function to convert the numbers in a nested list.我还创建了一个 function 来转换嵌套列表中的数字。 Please note that you cannot store characters and numerics in the same vector.
请注意,您不能将字符和数字存储在同一个向量中。
I hope this would help you.我希望这会对你有所帮助。
library(tidyverse)
func_parse_list <- function(l){
if(length(l)>1){
map(l, func_parse_list) %>% return()
}else{
parse_guess(l) %>% return()
}
}
list('a' = list('1', '2'),
'b' = list(
'c' = list('3', 'x'),
'd' = c('4', 'z'),
'e' = '5')) %>%
func_parse_list()
#> $a
#> $a[[1]]
#> [1] 1
#>
#> $a[[2]]
#> [1] 2
#>
#>
#> $b
#> $b$c
#> $b$c[[1]]
#> [1] 3
#>
#> $b$c[[2]]
#> [1] "x"
#>
#>
#> $b$d
#> $b$d[[1]]
#> [1] 4
#>
#> $b$d[[2]]
#> [1] "z"
#>
#>
#> $b$e
#> [1] 5
Created on 2021-12-05 by the reprex package (v2.0.1)由reprex package (v2.0.1) 于 2021 年 12 月 5 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.