R:如何将子字符串应用于嵌套列表?
我正在寻找在 tibble 内对嵌套列表进行子串,特别是限制列表中的字符数。就我而言,这里是感兴趣的对象:
my_list <- list(
a =
tibble(
code = c("ax","yz"),
affected_rows =
c(list(1:10),list(200))
),
b =
tibble(
workid = c("123","456"),
sheet = c("sheet1", "sheet2")
)
)
我希望获取 affected_rows
列列表,并使用数字 1:10 对第一个列表进行子串,以便它只有 4 个字符。不确定在整个列表上执行操作时解决此问题的最佳方法是什么。
预期输出: 我期望更改此输出(因此列表的 nchar 减少到 4):
my_list[1]$a$affected_rows[1]
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
to something like:
[[1]]
[1] 1 2
到目前为止,我已尝试以下操作但没有成功:
lapply(my_list, function(y) {
y %>% dplyr::mutate(across(where(is.list), ~ substring(.x,0,4)))
}
)
I am looking to substring a nested list inside a tibble, specifically limiting the number of characters in the list. In my case here is the object of interest:
my_list <- list(
a =
tibble(
code = c("ax","yz"),
affected_rows =
c(list(1:10),list(200))
),
b =
tibble(
workid = c("123","456"),
sheet = c("sheet1", "sheet2")
)
)
I am looking to take the affected_rows
column list and substring the first list with the numbers 1:10 so that it only has 4 characters. Not sure what's the best way to approach this when performing the operation on the entire list.
Output expected:
I am expecting to change the output of this (so the nchar of the list is brought down to 4):
my_list[1]$a$affected_rows[1]
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
to something like:
[[1]]
[1] 1 2
I've tried the following thus far with no success:
lapply(my_list, function(y) {
y %>% dplyr::mutate(across(where(is.list), ~ substring(.x,0,4)))
}
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它是整数向量而不是字符串。因此,我们可能需要检查以应用
substring
It is a vector of integers and not a string. So, we may need a check to apply
substring