gpt4 book ai didi

r - 通过匹配R中的字符串将行转换为列

转载 作者:行者123 更新时间:2023-12-04 22:40:03 24 4
gpt4 key购买 nike

我在列表中有行数,例如 '

[1,]  "Home"
[2,] "A"
[3,] "B"
[4,] "C"
[5,] "Home"
[6,] "D"
[7,] "E"
[8,] "Home"
[9,] "F"
[10,] "G"
[11,] "H"
[12,] "I"

这些行是动态出现的……在“Home”之后可以有两个、三个、四个、五个或更多子类别……所以绑定(bind)不起作用……我有超过 5000 行,而“Home”在每个子类别的开始..

我希望它看起来像这样。
       [,1]   [,2] [,3] [,4] [,5]

[1,] "Home" "A" "B" "C"
[2,] "Home" "D" "E"
[3,] "Home" "F" "G" "H" "I"

或者

我还使用转置将所有行转换为列
并使用转置我得到了。
   [,1]    [,2] [,3] [,4]  [,5]   [,6]  [,7]  [,8]   [,9] [,10] [,11] [,12]

"Home" "A" "B" "C" "Home" "D" "E" "Home" "F" "G" "H" "I"

任何解决方案都对我有用,要么使用“Home”的字符串匹配将行转换为列
或者
使用“Home”字符串匹配(转置一个)将列转换为行......

数据
x <- c("Home", "A", "B", "C", "Home", "D", "E", "Home", "F", "G", "H", "I")
x <- matrix(x)

问题已解决...谢谢您的回复...
我做了其他方式...通过在循环中运行它并在每个节点结束后添加行
List <- c() 

#loop start
nodes <- html_nodes(file,".class a b c ") %>% html_text()
List[[length(List)+1]] = nodes
#loop ends

library(stringi)
catdf <- stri_list2matrix(List, byrow = TRUE)
catdf <- as.data.frame(catdf)

最佳答案

# create the data
x <- as.matrix(c("Home", "A", "B", "C", "Home", "D", "E", "Home", "F" ,"G" ,"H" ,"I"))

# split the data into a list of vectors, wherever "Home" is found
rowstarts <- x == "Home"
rowlist <- split(x, cumsum(rowstarts))

然后我们可以使用 plyrldply将列表绑定(bind)到单个数据框的函数:
> plyr::ldply(rowlist, rbind)[-1]
1 2 3 4 5
1 Home A B C <NA>
2 Home D E <NA> <NA>
3 Home F G H I

把所有这些放在一起,就形成了一个简短的单行字:
ldply(split(x, cumsum(x == "Home")), rbind)[-1]

关于r - 通过匹配R中的字符串将行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49498439/

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