gpt4 book ai didi

R数据转换

转载 作者:行者123 更新时间:2023-12-04 23:27:58 26 4
gpt4 key购买 nike

我有一个 R 数据框,如下所示:

z = as.data.frame(list(Col1=c("a","c","e","g"),Col2=c("b","d","f","h"),Col3=c("1,2,5","3,5,7","9,8","1")))
> z
Col1 Col2 Col3
1 a b 1,2,5
2 c d 3,5,7
3 e f 9,8
4 g h 1

(第三列是带有逗号分隔值的文本列。)我想将其转换为这样的数据框:
a    b    1
a b 2
a b 5
c d 3
c d 5
c d 7
e f 9
e f 8
g h 1

任何人都可以建议一种使用apply来完成此操作的方法吗?我正在使用下面的命令关闭,但它不太正确。任何关于更有效的方法的建议也将不胜感激......
> apply(z,1,function(a){ids=strsplit(as.character(a[3]),",")[[1]];out<-c();for(id in ids){out<-rbind(out,c(a[1:2],id))};return(out)})
[[1]]
Col1 Col2
[1,] "a" "b" "1"
[2,] "a" "b" "2"
[3,] "a" "b" "5"

[[2]]
Col1 Col2
[1,] "c" "d" "3"
[2,] "c" "d" "5"
[3,] "c" "d" "7"

[[3]]
Col1 Col2
[1,] "e" "f" "9"
[2,] "e" "f" "8"

[[4]]
Col1 Col2
[1,] "g" "h" "1"

最佳答案

您可以使用 ddply .

library(plyr)
ddply(z, c("Col1", "Col2"), summarize,
Col3=strsplit(as.character(Col3),",")[[1]]
)

关于R数据转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9427404/

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