在此示例中,我有两个列表
seg.layer.borderWidth = 1
seg.layer.cornerRadius = seg.bounds.height / 2
seg.layer.masksToBounds = true
seg.apportionsSegmentWidthsByContent = true
,我想通过添加相应元素在tiers <- list("tier 1", "tier 2", "tier 3")
main <- list(data.frame(a = c("this", "that")),
data.frame(a = c("the other", "that too")),
data.frame(a = c("once more", "kilgore trout")))
中的值来mutate()
中的每个列表元素(即data.frame()
)。我以为main
会做到:
tiers
但是我得到了意外的结果
mapply()
而我期望的是
library(dplyr)
mapply(function(x, y) y %>% mutate(tier = x), tiers, main)
我正确使用> mapply(function(x, y) y %>% mutate(tier = x), tiers, main)
[,1] [,2] [,3]
a factor,2 factor,2 factor,2
tier Character,2 Character,2 Character
吗?如果不是,是否应该使用某些东西来获得期望的结果?我应该指出,实际数据可能最多包含[[1]]
a tier
1 this tier 1
2 that tier 1
[[2]]
a tier
1 the other tier 2
2 that too tier 2
[[3]]
a tier
1 once more tier 3
2 kilgore trout tier 3
个列表元素;我无法用mapply()
来硬编码任何值。
答案 0 :(得分:2)
您需要的是在您的SIMPLIFY = FALSE
通话中添加mapply
library(dplyr)
mapply(function(x, y) y %>% mutate(tier = x), tiers, main, SIMPLIFY = FALSE)
# a tier
#1 this tier 1
#2 that tier 1
#[[2]]
# a tier
#1 the other tier 2
#2 that too tier 2
#[[3]]
# a tier
#1 once more tier 3
#2 kilgore trout tier 3
?mapply
说
SIMPLIFY-尝试将结果简化为向量,矩阵或更高维的数组;
SIMPLIFY
参数默认为TRUE
中的mapply
和FALSE
中的Map
Map(function(x, y) y %>% mutate(tier = x), tiers, main)
如果您想将所有内容保留在基数R中,则可以使用cbind
Map(cbind, main, tiers)
答案 1 :(得分:2)
另外,请考虑将within
或transform
与Map
(列出mapply
的版本包装器)并避免为一个功能mutate
加载程序包:< / p>
Map(function(x, y) within(y, tier <- x), tiers, main)
Map(function(x, y) transform(y, tier = x), tiers, main)
答案 2 :(得分:2)
在基础R
中,如果您命名Map
参数,则可以将data.frame
与函数tier
一起使用:
Map(data.frame, main, tier=tiers)
# [[1]]
# a tier
# 1 this tier 1
# 2 that tier 1
#
# [[2]]
# a tier
# 1 the other tier 2
# 2 that too tier 2
#
# [[3]]
# a tier
# 1 once more tier 3
# 2 kilgore trout tier 3
答案 3 :(得分:1)
我们可以在tidyverse
中使用map2
library(tidyverse)
map2(main, tiers, ~ .x %>%
mutate(tiers = .y))
#[[1]]
# a tiers
#1 this tier 1
#2 that tier 1
#[[2]]
# a tiers
#1 the other tier 2
#2 that too tier 2
#[[3]]
# a tiers
#1 once more tier 3
#2 kilgore trout tier 3