【问题标题】:same names matrix R同名矩阵R
【发布时间】:2020-07-13 14:55:06
【问题描述】:
for usability
loopx<- list()
loopx[[1]] <- c(3,3)
loopx[[2]] <- c(2,4)
loopx[[3]] <- c(4,44)
loopx[[4]] <- c(8,5)
loopx[[5]] <- c(4,4)

它返回一个 5 层列表 例如

循环

[[1]] [1] 3 3

[[2]] [1] 2 4

[[3]] [1] 4 44

[[4]] [1] 8 5

[[5]] [1] 4、4

那我走了

names(loopx) <- c("one", "two", "three", "four", "five")
unlist(loopx)
one1  one2 two1 two2 three1 thre2 four1 four2 five1 six2 
 3      3   2    4    4      44    8     5    4     4 

如何在矩阵中取相同的名称,而 1 和 2 不重复

【问题讨论】:

  • 你的预期输出是什么?

标签: r list matrix


【解决方案1】:

您可以使用sub 删除数字并使用setNames 重新分配名称。

unloopx <- unlist(loopx)
setNames(unloopx, sub("\\d+", "", names(unloopx)))

#  one   one   two   two three three  four  four  five  five 
#    3     3     2     4     4    44     8     5     4     4

【讨论】:

  • 对不起应该更清楚,如果列名是 one1, one1, two2, two2。您说的代码将删除该号码。我该如何度过这个
【解决方案2】:

代替unlisting,我们可以将stack它转换为两列data.frame,然后从列转换为命名vector

with(stack(loopx)[2:1], setNames(values, ind))
# one   one   two   two three three  four  four  five  five 
#   3     3     2     4     4    44     8     5     4     4

或者我们使用unlistuse.names = FALSE 并通过replicating names 来设置名称

setNames(unlist(loopx, use.names = FALSE), rep(names(loopx), lengths(loopx)))
#  one   one   two   two three three  four  four  five  five 
#   3     3     2     4     4    44     8     5     4     4  

或者使用enframe/deframe 来自tibble

library(tibble)
library(tidyr)
enframe(loopx) %>% 
       unnest(c(value)) %>%
       deframe
#  one   one   two   two three three  four  four  five  five 
#    3     3     2     4     4    44     8     5     4     4 

【讨论】:

    猜你喜欢
    • 2019-05-05
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多