1

我有一个清单:

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中的列表元素中的那些值:18190nchar

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=""))}}

}

    )

但我只得到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

我究竟做错了什么?:(

此致!

4

3 回答 3

4

您可以将过程大大简化为两行:

使用lapplytable获取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))
于 2013-07-02T13:22:17.033 回答
3

你的第一个if(nchar(kk==0))应该是if(nchar(kk)==0).

于 2013-07-02T13:18:39.047 回答
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
于 2013-07-02T13:27:35.660 回答