Transforming data.frame in R

前端 未结 2 1279
醉梦人生
醉梦人生 2021-01-21 06:58

I have the following data frame:

foo <- data.frame( abs( cbind(rnorm(3),rnorm(3, mean=.8),rnorm(3, mean=.9),rnorm(3, mean=1))))
colnames(foo) <- c(\"w\",\"         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 07:24

    There are several ways to do this. Here's one:

    set.seed(1)
    foo <- data.frame( abs( cbind(rnorm(3),
                                  rnorm(3, mean=.8),
                                  rnorm(3, mean=.9),
                                  rnorm(3, mean=1))))
    colnames(foo) <- c("w","x","y","z")
    rownames(foo) <- c("n","q","r")
    foo
    #           w          x        y         z
    # n 0.6264538 2.39528080 1.387429 0.6946116
    # q 0.1836433 1.12950777 1.638325 2.5117812
    # r 0.8356286 0.02046838 1.475781 1.3898432
    data.frame(rows = row.names(foo), stack(foo))
    #    rows     values ind
    # 1     n 0.62645381   w
    # 2     q 0.18364332   w
    # 3     r 0.83562861   w
    # 4     n 2.39528080   x
    # 5     q 1.12950777   x
    # 6     r 0.02046838   x
    # 7     n 1.38742905   y
    # 8     q 1.63832471   y
    # 9     r 1.47578135   y
    # 10    n 0.69461161   z
    # 11    q 2.51178117   z
    # 12    r 1.38984324   z
    

提交回复
热议问题