gpt4 book ai didi

R编程: Creating a list of paired elements

转载 作者:行者123 更新时间:2023-12-01 12:45:16 26 4
gpt4 key购买 nike

我有一个元素列表说:

l <- c("x","ya1","xb3","yb3","ab","xc3","y","xa1","yd4")

在这个列表中,我想列出匹配的 x,y 对,即

(("xa1" "ya1") ("xb3" "yb3") ("x" "y"))

本质上,我需要捕获 X 元素、Y 元素,然后将它们配对:我知道如何进行 X、Y 提取部分:

xelems <- grep("^x", l, perl=TRUE, value=TRUE)
yelems <- grep("^y", l, perl=TRUE, value=TRUE)

1. xElem == yElem # if xElem and yElem are one char long, i.e. 'x' and 'y'    
2. substr(xElem,1,nchar(xElem)) == substr(yElem,1,nchar(yElem))

没有顺序,即匹配的 xElem 和 yElem 可以放在任何位置。

但是我对下一部分不是很确定。我比较熟悉 SKILL programming language (SKILL 是 LISP 的衍生物)我是这样写的:

procedure( get_xy_pairs(inputList "l")
let(( yElem (xyPairs nil) xList yList)
xList=setof(i inputList rexMatchp("^x" i))
yList=setof(i inputList rexMatchp("^y" i))
when(xList && yList
unless(length(xList)==length(yList)
warn("xList and yList mismatch : %d vs %d\n" length(xList) length(yList))
)
foreach(xElem xList
if(xElem=="x"
then yElem="y"
else yElem=strcat("y" substring(xElem 2 strlen(xElem)))
)
if(member(yElem yList)
then xyPairs=cons(list(xElem yElem) xyPairs)
else warn("x element %s has no matching y element \n" xElem)
)
)
)
xyPairs
)
)

当在 l 上运行时,这将返回

get_xy_pairs(l)
*WARNING* x element xc3 has no matching y element
(("xa1" "ya1") ("xb3" "yb3") ("x" "y"))

由于我对 R 还是个新手,如果你们能提供帮助,我将不胜感激。此外,我知道 R 的人倾向于避免 for 循环而更喜欢 lapply ?

最佳答案

也许这样的事情会奏效。 (仅在您的示例数据上进行了测试。)

## Remove any item not starting with x or y
l2 <- l[grepl("^x|^y", l)]

## Split into a list of items starting with x
## and items starting with y
L <- split(l2, grepl("^x", l2))

## Give "names" to the "starting with y" group
names(L[[1]]) <- gsub("^y", "x", L[[1]])

## Use match to match the names in the y group with
## the values from the x group. This results in a
## nice named vector with the pairs you want
Matches <- L[[1]][match(L[[2]], names(L[[1]]), nomatch=0)]
Matches
# x xb3 xa1
# "y" "yb3" "ya1"

作为data.frame:

MatchesDF <- data.frame(x = names(Matches), y = unname(Matches))
MatchesDF
# x y
# 1 x y
# 2 xb3 yb3
# 3 xa1 ya1

关于R编程: Creating a list of paired elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695031/

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