将数据框元素转换为摘要表

时间:2018-02-22 04:47:21

标签: r dataframe split

我有一个数据框,我想创建一个包含所有单元格值的表,以及它们的行名和列名。例如,

a <- c(1:4)
df <- matrix(a, nrow = 2, ncol = 2, byrow = T)
rownames(df) <- c("Paul", "Matt")
colnames(df) <- c("Beach", "Hike")
df <- as.data.frame(df)
df

我希望输出是一个包含以下列的数据框:

Paul | 1 | Beach
Paul | 2 | Hike
Matt | 3 | Beach
Matt | 4 | Hike

我需要为一个非常大的数据集排序行和列的所有组合的数值,这样如果有人能帮我解决这个问题很棒:)

谢谢!

3 个答案:

答案 0 :(得分:1)

如果您不关心rownames df stack,您可以使用基地R stack(df); # values ind #1 1 Beach #2 3 Beach #3 2 Hike #4 4 Hike

tidyverse

require(tidyverse); df %>% gather(key, values, 1:2) %>% mutate(id = rep(rownames(df), ncol(df))) %>% arrange(desc(id)); # key values id #1 Beach 1 Paul #2 Hike 2 Paul #3 Beach 3 Matt #4 Hike 4 Matt 方法:

import java.io.IOException;
import java.net.URI;

import javax.websocket.*;

@ClientEndpoint
public class Client {

    Session session;

    private final static String url = "ws://echo.websocket.org";

    public static void main(String[] args) throws Exception, IOException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        System.out.println("connecting...");
        container.connectToServer(Client.class,
                URI.create(url));
    }


    @OnMessage
    public void newMessage(String message, Session session) {
        System.out.println(message);
    }
    @OnOpen
    public void newConnection(Session session) throws IOException {
        this.session = session;
        System.out.println("The connection has been started");
        session.getBasicRemote().sendText("hello");

    }
    @OnClose
    public void disconnection() {
        System.out.println("The connection has been ended");
    }
}

答案 1 :(得分:0)

 library(tidyverse)
  df %>% 
  rownames_to_column(var="name") %>% 
  gather(key,value,-name) %>% 
  arrange(value)

  name   key value
1 Paul Beach     1
2 Paul  Hike     2
3 Matt Beach     3
4 Matt  Hike     4

答案 2 :(得分:0)

res_df = data.frame()
for(x in rownames(df)){
   for(y in colnames(df)){
      res_df = rbind(res_df, as.data.frame(t(c(person=x, count=df[x,y], activity=y))))
   }
}


  person count activity
1   Paul     1    Beach
2   Paul     2     Hike
3   Matt     3    Beach
4   Matt     4     Hike