我有一个清单:
xxx
[[1]]
[1] 1899 99 99 97 97 97 97 97
[[2]]
[1] 86 86 86 86 86 86 86
[[3]]
[1] 1897 97 97 97 97 97 97 97 97 97
[[4]]
[1] 3 3 3 3
[[5]]
[1] 1883 83 83 83 83 83 83 83 83 83
Dput:
list(c(1899L, 99L, 99L, 97L, 97L, 97L, 97L, 97L), c(86L, 86L,
86L, 86L, 86L, 86L, 86L), c(1897L, 97L, 97L, 97L, 97L, 97L, 97L,
97L, 97L, 97L), c(3L, 3L, 3L, 3L), c(1883L, 83L, 83L, 83L, 83L,
83L, 83L, 83L, 83L, 83L))
然后我在每个列表元素中选择最常用的值,并按列表元素的长度重复该值:
xxxh=lapply(xxx,function(x) {
a=max(rle(sort(x))[[1]])
b=rle(sort(x))[[2]][which(rle(sort(x))[[1]]==a)]
hh=rep(b,length(x))
return(hh)
})
我收到警告"In max(rle(sort(x))[[1]]) : no non-missing arguments to max; returning -Inf"
结果是
xxxh
[[1]]
[1] 97 97 97 97 97 97 97 97
[[2]]
[1] 86 86 86 86 86 86 86
[[3]]
[1] 97 97 97 97 97 97 97 97 97 97
[[4]]
[1] 3 3 3 3
[[5]]
[1] 83 83 83 83 83 83 83 83 83 83
然后我尝试使用paste
或18
190
上面列表元素中的nchar
值,具体取决于每个列表元素的第一个元素的xxxm=lapply(xxxh,function(x) {
kk=x[1]
if(nchar(kk==0)) { kk<-0 }
else {
if (nchar(kk)==1) {as.numeric(paste(190,kk,sep=""))} else {
if (nchar(kk)==2) as.numeric(paste(18,kk,sep=""))}}
}
)
:< / p>
zeros
但我只得到xxxm
[[1]]
[1] 0
[[2]]
[1] 0
[[3]]
[1] 0
[[4]]
[1] 0
[[5]]
[1] 0
......
xxxm
[[1]]
[1] 1897
[[2]]
[1] 1896
[[3]]
[1] 1897
[[4]]
[1] 1903
[[5]]
[1] 1883
我想得到:
{{1}}
我做错了什么?:(
最诚挚的问候!
答案 0 :(得分:4)
您可以将流程简化为两行:
将lapply
与table
和which.max
一起使用以获取模式。 (统计模式,而不是R语言模式)
然后使用ifelse
相应地粘贴,如果值小于10
# find the most frequent value, using `table` & `which.max`
mode.mylist <- lapply(mylist, function(x) names(which.max(table(x))))
# paste values as needed. No need to count characters. Instead check if the value is less than 10. (R coerces to numeric)
ifelse(mode.mylist < 10, paste0("190", mode.mylist), paste0("18", mode.mylist))
[1] "1897" "1886" "1897" "1903" "1883"
<小时/>
mylist
是您的起始列表,例如:
mylist <- list(c(1899L, 99L, 99L, 97L, 97L, 97L, 97L, 97L), c(86L, 86L, 86L, 86L, 86L, 86L, 86L), c(1897L, 97L, 97L, 97L, 97L, 97L, 97L, 97L, 97L, 97L), c(3L, 3L, 3L, 3L), c(1883L, 83L, 83L, 83L, 83L, 83L, 83L, 83L, 83L, 83L))
答案 1 :(得分:3)
您的第一个if(nchar(kk==0))
应为if(nchar(kk)==0)
。
答案 2 :(得分:2)
你也可以这样做
xxxm <- lapply(xxx,
function(x) rep(which.max(tabulate(x)), length(x)))
lapply(xxxm, function(x)
as.numeric(paste0(c(190, 18)[nchar(unique(x))], unique(x))))
[[1]]
[1] 1897
[[2]]
[1] 1886
[[3]]
[1] 1897
[[4]]
[1] 1903
[[5]]
[1] 1883