Hello i have this list
你好我有这个清单
LIST<-list(list("DC,MD,MA,Washigton,Baltimore,Boston,France,Turkey,China"),
list("DC,MD,Washington,Baltimore,France,Turkey"),
list("DC,Washington,France,Turkey,China")
I want to change the order of the strings of the sublists according to this logic:
我想根据这个逻辑更改子列表的字符串的顺序:
LIST<-list(list("DC,Washington,MD,Baltimore,MA,Boston,France,Turkey,China"),
list("x1,y1,x2,y2,z1,z2,z3"),
list("x1,y1,z1,z2,z3"))
Note that x and y have the same count and can be up to 3. Z do not have count restriction. I do not want of course the change the order manually for each sublist but with an automated way.
请注意,x和y具有相同的计数,最多可以为3. Z没有计数限制。我当然不希望为每个子列表手动更改订单,而是使用自动方式。
1 个解决方案
#1
2
library(magrittr)
fun=function(string){
lapply(strsplit(string,","),function(x)sub("([a-z])([0-9])","\\2\\1",x)%>%
sort()%>%sub("([0-9])([a-z])","\\2\\1",.)%>%paste(collapse=","))
}
rapply(LIST,fun,how="list")
After edition:
fun=function(string,NO){
lapply(strsplit(string,","),function(x)
paste(c(by(x, c(s<-rep(1:NO,2),rep(0,length(x)-length(s)))
,paste0,collapse=",")),collapse=", "))
}
rapply(LIST,fun,how="list",NO=3)
#1
2
library(magrittr)
fun=function(string){
lapply(strsplit(string,","),function(x)sub("([a-z])([0-9])","\\2\\1",x)%>%
sort()%>%sub("([0-9])([a-z])","\\2\\1",.)%>%paste(collapse=","))
}
rapply(LIST,fun,how="list")
After edition:
fun=function(string,NO){
lapply(strsplit(string,","),function(x)
paste(c(by(x, c(s<-rep(1:NO,2),rep(0,length(x)-length(s)))
,paste0,collapse=",")),collapse=", "))
}
rapply(LIST,fun,how="list",NO=3)