强制imap在命名向量上使用索引 最简单的reprex和问题
我有世界上最简单的命名向量,比如:强制imap在命名向量上使用索引 最简单的reprex和问题,r,purrr,R,Purrr,我有世界上最简单的命名向量,比如: vec <- seq(101, 126) names(vec) <- letters head(vec) # a b c d e f #101 102 103 104 105 106 这种行为是完全正常的:.x迭代值,.y迭代名称(如名称),如果向量已命名,则迭代索引(如沿排序) 我想知道是否有一种方式可以表现为输入向量没有命名,即有一种方式可以访问索引而不是名称。 预期产出为: # a b
vec <- seq(101, 126)
names(vec) <- letters
head(vec)
# a b c d e f
#101 102 103 104 105 106
这种行为是完全正常的:.x
迭代值,.y
迭代名称(如名称
),如果向量已命名,则迭代索引(如沿
排序)
我想知道是否有一种方式可以表现为输入向量没有命名,即有一种方式可以访问索引而不是名称。
预期产出为:
# a b c d e f
#"101_1" "102_2" "103_3" "104_4" "105_5" "106_6"
当前解决方法
我目前正在使用purrr::map2
作为解决方案,但我觉得这个解决方案并不优雅(过于冗长)
补遗 提供一个非常简单的reprex的问题是,人们试图解决我的问题,而不是回答我的问题。太好了,但不是我想要的。我的问题是连接
.x
和.y
,而不是
更精致的reprex
假设我有一些观测值之间的距离矩阵:
mat <- matrix(c(0, 1, 2, 1, 0, 4, 2, 4, 0), 3, 3)
nms <- letters[seq(3)]
names(nms) <- nms # Without this, I could use imap
dimnames(mat) <- list(nms, nms)
mat
# a b c
#a 0 1 2
#b 1 0 4
#c 2 4 0
现在,我正在使用map2
解决这个问题
colnames(mat) %>% map2_dbl(seq_along(.), ~sd(mat[-.y,.x]))
#[1] 0.7071068 2.1213203 1.4142136
如果您想使用
imap
一种解决方法是使用match
library(purrr)
vec %>% imap_chr(~paste(.x, match(.y, names(vec)), sep="_")) %>% head
# a b c d e f
#"101_1" "102_2" "103_3" "104_4" "105_5" "106_6"
我们还可以使用
map\u chr
迭代其索引
vec[] <- seq_along(vec) %>% map_chr(~paste(vec[.x], .x, sep = "_"))
head(vec)
# a b c d e f
#"101_1" "102_2" "103_3" "104_4" "105_5" "106_6"
vec[]%map\u chr(~paste(vec[.x],.x,sep=“”))
主管(vec)
#a b c d e f
#"101_1" "102_2" "103_3" "104_4" "105_5" "106_6"
我们可以使用stru c
和imap
library(stringr)
library(purrr)
vec %>%
imap_chr(~ str_c(.x, match(.y, names(vec)), sep="_"))
您的
map2
解决方案可以简化为%>%map2\u chr(seq\u-along(.),~paste(.x,.y,sep=“”))
或更简洁的%>%map2\u-chr(seq\u-along(.),paste,sep=“”
。关于:vec[]
library(purrr)
vec %>% imap_chr(~paste(.x, match(.y, names(vec)), sep="_")) %>% head
# a b c d e f
#"101_1" "102_2" "103_3" "104_4" "105_5" "106_6"
vec[] <- seq_along(vec) %>% map_chr(~paste(vec[.x], .x, sep = "_"))
head(vec)
# a b c d e f
#"101_1" "102_2" "103_3" "104_4" "105_5" "106_6"
library(stringr)
library(purrr)
vec %>%
imap_chr(~ str_c(.x, match(.y, names(vec)), sep="_"))