如何修改和粘贴列表中的值

时间:2013-07-03 10:05:23

标签: r lapply if-statement

我有一个清单:

my.list
[[1]]
[1] 1899 1899 1899 1899 1899 1899 1899 1899

[[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

[[6]]
[1] 2 2 2 2 2 2 2 2

[[7]]
[1] 10 10 10 10 10 10 10 10

Dput:

list(c(1899L, 1899L, 1899L, 1899L, 1899L, 1899L, 1899L, 1899L
), c(86L, 86L, 86L, 86L, 86L, 86L, 86L), c(97L, 97L, 97L, 97L, 
97L, 97L, 97L, 97L, 97L, 97L), c(3L, 3L, 3L, 3L), c(83L, 83L, 
83L, 83L, 83L, 83L, 83L, 83L, 83L, 83L), c(2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L),c(10L, 10L, 10L, 10L, 10L, 10L ))

我想修改每个列表元素中的值,以便得到:

my.listfinal
    [[1]]
    [1] 1899 1899 1899 1899 1899 1899 1899 1899

    [[2]]
    [1] 1886 1886 1886 1886 1886 1886 1886 

    [[3]]
     [1] 1897 1897 1897 1897 1897 1897 1897 1897 1897 1897 

    [[4]]
    [1] 1903 1903 1903 1903 

    [[5]]
     [1] 1883 1883 1883 1883 1883 1883 1883 1883 1883 1883 

    [[6]]
    [1] 1902 1902 1902 1902 1902 1902 1902 1902 

    [[7]]
    [1] 1910 1910 1910 1910 1910 1910 1910 1910 

换句话说,我想用1901,18粘贴值,或者如果nchar==4

那么将它们单独留下

我试过了:

xxfinal=lapply(xxxm,function(x) { 

ifelse(unique(x) <10,paste0("190", x),ifelse(unique(x)==10,paste0("19",x),
ifelse(nchar(unique(x))==2 & unique(x)>10,paste0("18",x),x))) 

} 
)

但这给了我一个error

    Error in ifelse(unique(x) == 10, paste0("19", x), ifelse(nchar(unique(x) ==  : 
  unused argument (x)

我做错了什么?

编辑:

有效:

my.listfinal=lapply(my.list,function(x) { 

as.numeric(ifelse(x<10,paste0("190", x),ifelse(x==10,paste0("19",x),
ifelse(nchar(x)==2 & x>10,paste0("18",x),x)))) 

} )

感谢您的评论!

1 个答案:

答案 0 :(得分:3)

这是一种方法:

lapply(my.list, function(x) x %% 1800 + 1800 + 100 * (x <= 10))

结果:

[[1]]
[1] 1899 1899 1899 1899 1899 1899 1899 1899

[[2]]
[1] 1886 1886 1886 1886 1886 1886 1886

[[3]]
 [1] 1897 1897 1897 1897 1897 1897 1897 1897 1897 1897

[[4]]
[1] 1903 1903 1903 1903

[[5]]
 [1] 1883 1883 1883 1883 1883 1883 1883 1883 1883 1883

[[6]]
[1] 1902 1902 1902 1902 1902 1902 1902 1902

[[7]]
[1] 1910 1910 1910 1910 1910 1910