gpt4 book ai didi

r - 添加一个带有 apply 和 gregexpr 的新列

转载 作者:行者123 更新时间:2023-12-05 00:13:21 28 4
gpt4 key购买 nike

我有一个包含多个子列表的主列表,其中包含许多 data.frames。
见下面的例子:

sublist1 <- list(data.frame('Position' = c(1,2,3), 'Color' = c("black-white-
silver-red","black-white-red","black-white")),
data.frame('Position' = c(1,2,3), 'Color' = c("black-white-
pink-gold-red","black-white","black")) )

sublist2 <- list(data.frame('Position' = c(1,2,3), 'Color' = c("black-
silver-red","black-white-red","white")),
data.frame('Position' = c(1,2,3), 'Color' = c("pink-gold-
red","black-white","black-white")) )

mainList <- list(sublist1, sublist2)

我正在尝试向每个名为“Color_Count”的 data.frame 添加一个新列,它将返回 data.frame 每一行的不同颜色的数量。理想情况下,输出如下所示:
> mainList
[[1]]
[[1]][[1]]
Position Color Color_Count
1 1 black-white-silver-red 4
2 2 black-white-red 3
3 3 black-white 2

[[1]][[2]]
Position Color Color_Count
1 1 black-white-pink-gold-red 5
2 2 black-white 2
3 3 black 1
....

我曾尝试使用 gregexpr 函数以及 lapply 但输出看起来不像我想要的。

我真的很感激这里的一些帮助。
先感谢您。

此致,

最佳答案

如果我们可以假设每种颜色都由一个破折号“-”分隔,我们可以简单地计算颜色列中破折号的数量并加 1:

foo <- function(lst, col) {
lapply(lst, function(x)
if(!is.data.frame(x)) foo(x, col)
else transform(x, ColorCount = stringr::str_count(x[[col]], "-")+1))}

foo(mainList, "Color")

#[[1]]
#[[1]][[1]]
# Position Color ColorCount
#1 1 black-white-\nsilver-red 4
#2 2 black-white-red 3
#3 3 black-white 2
#
#[[1]][[2]]
# Position Color ColorCount
#1 1 black-white-pink-gold-red 5
#2 2 black-white 2
#3 3 black 1
#...

我正在使用 stringr库来计算计数,但您也可以使用基本 R 或 stringi 或其他方法。

我建了 foo作为递归函数,因为您有一个列表列表,我们只想处理最内部列表中的 data.frames。

关于r - 添加一个带有 apply 和 gregexpr 的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785884/

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