gpt4 book ai didi

r - 在 R 中展开矩阵的列

转载 作者:行者123 更新时间:2023-12-05 01:14:22 30 4
gpt4 key购买 nike

我有一个如下所示的矩阵“a”:

a<-rbind(c("a1","ost1;ost2;ost3","utr;body;pro"),
c("a2","idh1;idh2","pro;body"),
c("a3","dnm1","body"))
>a
[,1] [,2] [,3]
[1,] "a1" "ost1;ost2;ost3" "utr;body;pro"
[2,] "a2" "idh1;idh2" "pro;body"
[3,] "a3" "dnm1" "body"

我想得到这样的矩阵“b”

     [,1] [,2]   [,3]  
[1,] "a1" "ost1" "utr"
[2,] "a1" "ost2" "body"
[3,] "a1" "ost3" "pro"
[4,] "a2" "idh1" "pro"
[5,] "a2" "idh2" "body"
[6,] "a3" "dnm1" "body"

好的,明白了:

b<-do.call(rbind, (apply(a, 1, function(x) {do.call(cbind, strsplit(x,";"))})))

最佳答案

你的解决方案,没有不必要的括号:

do.call(rbind, apply(a, 1, function(x) do.call(cbind, strsplit(x, ";"))))

这也有效:

do.call(rbind, lapply(apply(a, 1, strsplit, ';'), do.call, what = cbind))

并不是说使用匿名函数 (function(x){...}) 有什么问题,但有些人发现没有任何匿名函数更“优雅”。

关于r - 在 R 中展开矩阵的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17149691/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com