gpt4 book ai didi

r - 如何将列制作成R中的列名

转载 作者:行者123 更新时间:2023-12-01 23:00:13 25 4
gpt4 key购买 nike

我有一个 3 列的数据框,如下所示

    batsman1                 bowler1         timesOut
1 A Ashish Reddy A Ashish Reddy 0
2 A Ashish Reddy A Chandila 1
3 A Ashish Reddy A Choudhary 3
4 A Ashish Reddy A Dananjaya 0

我想转换上面的数据框,其中第二列变成列名,如下所示

    batsman1         A Ashish Reddy A Chandila A Choudhary A Danajaya

A Ashish Reddy. 0 1 3 0
A Chandila
A Choudhary
A Danajaya

最佳答案

一种方法可能是使用 xtabs

xtabs(timesOut ~ ., x)
# bowler1
#batsman1 1 A_Ashish_Reddy A_Chandila A_Choudhary A_Dananjaya
# A_Ashish_Reddy 0 0 1 3 0
# A_Chandila 0 0 0 0 0
# A_Choudhary 0 0 0 0 0
# A_Dananjaya 0 0 0 0 0

数据:

x <- read.table(text="    batsman1                 bowler1         timesOut
1 A_Ashish_Reddy A_Ashish_Reddy 0
2 A_Ashish_Reddy A_Chandila 1
3 A_Ashish_Reddy A_Choudhary 3
4 A_Ashish_Reddy A_Dananjaya 0")
x[1] <- factor(x[[1]], unique(unlist(x[1:2])))
x[2] <- factor(x[[2]], levels(x[,1]))

关于r - 如何将列制作成R中的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72097801/

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