【问题标题】:Converting cases to variables in R将案例转换为 R 中的变量
【发布时间】:2011-12-13 22:45:36
【问题描述】:

我有一个格式为 data_format1 的数据。在此基础上,我想将案例转换为变量以获得data_format2。

您可以在此处找到 data_format1:

ArticleID<-c(1, 2, 3, 3, 4)
Word<-c("a", "b", "b", "c", "c")
Freq<-c(2, 4, 6, 3, 2)
data_format1<-cbind(ArticleID, Word, Freq)

data_format1

     ArticleID Word Freq
[1,] "1"       "a"  "2" 
[2,] "2"       "b"  "4" 
[3,] "3"       "b"  "6" 
[4,] "3"       "c"  "3" 
[5,] "4"       "c"  "2" 

data_format2 在这里给出:

ArticleID_t<-c(1, 2, 3, 4)
a<-c(2, 0, 0, 0)
b<-c(0, 4, 6, 0)
c<-c(0, 0, 3, 2)
data_format2<-cbind(ArticleID_t, a, b, c)
data_format2

     ArticleID_t a b c
[1,]           1 2 0 0
[2,]           2 0 4 0
[3,]           3 0 6 3
[4,]           4 0 0 2

【问题讨论】:

    标签: r variables case


    【解决方案1】:

    这是一个经典的重塑问题 - 将数据从高格式转换为宽格式。 reshape2 包非常适合这种情况。

    注意:您需要先将数据转换为data.frame。请记住,cbind 将获取您的数据并创建一个数组,而不是 data.frame。所以在解决方案中,我使用data.frame(...) 重新创建您的数据。

    library(reshape2)
    data_format1 <- data.frame(ArticleID, Word, Freq)
    reshape2::dcast(data_format1, ArticleID~Word, sum)
    
      ArticleID a b c
    1         1 2 0 0
    2         2 0 4 0
    3         3 0 6 3
    4         4 0 0 2
    

    更多信息请参见?reshape2::dcast

    【讨论】:

    • 感谢安德烈。我马上测试你的答案,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多