2015-10-24 35 views
1

我的數據是以下形式的的R值[R生成從0向量計數不存在

data<-list(list(Name= "Value1",corresponding_set=c(1,2,3)), list(Name="AnotherKey",corresponding_set=c(4,5,3,4))) 

我所試圖獲得的格式

  1 2 3 4 5 
Key   1 1 1 0 0 
AnotherKey 0 0 1 2 1 

的數據幀我試過如下:

myfunc<-function(x){ 
    currValue<-x$corresponding_Set 
    for(i in 1:5){ 
    print(c(i,sum(currValue==i)) 
    } 
} 
sapply(data,myfunc) 

上面的代碼並打印我需要的價值,但在下面的格式

1 1 
2 1 
3 1 
4 0 
5 1 
1 0 
2 0 
3 0 
4 2 
5 1 

我的問題是

  1. 對於所使用的數據類型是「數據」的結構是否合適?如果不是,它應該如何設計。目前,這個數據是靜態的,我想這種方式保持它現在
  2. 我不能夠形成一個想法如何,我打印到網格格式(數據幀或矩陣)
向量轉換

任何幫助表示讚賞!

回答

2

通過將嵌套lists轉換爲data.frames,將它們綁定在一起,然後調用table,可以得到您要查找的結果。

data <- list(list(Name = "Value1", 
        corresponding_set = c(1, 2, 3)), 
      list(Name = "AnotherKey", 
        corresponding_set = c(4, 5, 3, 4))) 

# Convert each list element to a data.frame 
dfs <- lapply(data, as.data.frame) 
dfs 
# [[1]] 
#  Name corresponding_set 
# 1 Value1     1 
# 2 Value1     2 
# 3 Value1     3 
# 
# [[2]] 
#   Name corresponding_set 
# 1 AnotherKey     4 
# 2 AnotherKey     5 
# 3 AnotherKey     3 
# 4 AnotherKey     4 


# bind the two data.frames together 
df <- do.call(rbind, dfs) 
df 
#   Name corresponding_set 
# 1  Value1     1 
# 2  Value1     2 
# 3  Value1     3 
# 4 AnotherKey     4 
# 5 AnotherKey     5 
# 6 AnotherKey     3 
# 7 AnotherKey     4 

# build a table 
table(df) 
#    corresponding_set 
# Name   1 2 3 4 5 
# AnotherKey 0 0 1 2 1 
# Value1  1 1 1 0 0