2017-04-21 57 views
0

我想從reshape2使用dcast將數據幀從long轉換爲wide。reshape2 dcast非二進制運算符的非數字參數

我創建這樣一個數據幀:

> Person=c("A","A","A","A","B","B","C","C","C","C") 
> Object=c("car", "watch", "bike", "phone","car","skateboard","car","bike","motorcycle") 
> Value=c("1","1","1","1","1","1","1","1","1","1") 
> df=data.frame(Person, Object, Value) 

,並得到,

> df 
    Person  Object Value 
1  A  car  1 
2  A  watch  1 
3  A  bike  1 
4  A  phone  1 
5  B  car  1 
6  B skateboard  1 
7  C  car  1 
8  C  bike  1 
9  C motorcycle  1 
10  C   TV  1 

然後,dcast

> library(reshape2) 
> dcast(df, Person + Object, variable.var="Value", fun.aggregate=length) 
Error in Person + Object : non-numeric argument to binary operator 

爲什麼dcast將需要爲個人和對象的數值參數列嗎?

我試圖讓這個輸出:

Person car watch bike phone skateboard motorcycle TV 
    A  1  1  1  1    0    0  0 
    B  1  0  0  0    1    0  0 
    C  1  0  1  0    0    1  1 

*編輯* @neilfws找到了解決辦法:

dcast(df, Person ~ . + Object, variable.var="Value") 

然而,當數據幀從一個製表進口分隔文件:

df = read.table("Person_Object.tab", header=T, sep="\t") 

the sa我dcast命令返回:

Error in eval(expr, envir, enclos) : object 'Person' not found 
+0

你需要指定一個公式,包含'〜',否則,[R認爲你試圖把兩個數相加。也許'個人+對象〜.'? – neilfws

+1

@neilfws:謝謝! 'dcast(df,Person〜。+ Object,variable.var =「Value」)'種類的作品。 – user31888

+0

但是從文件導入相同的數據幀會返回不同的錯誤(請參閱上面的編輯) – user31888

回答

0

顯示如何填充空單元格。

Person=c("A","A","A","A","B","B","C","C","C","C") 
Object=c("car", "watch", "bike", "phone","car","skateboard","car","bike","motorcycle", "TV") 
Value=c("1","1","1","1","1","1","1","1","1","1") 

# note the extra parameter StringsAsFactors - needed so that "0" can be used 
df=data.frame(Person, Object, Value, stringsAsFactors = FALSE) 

library(reshape2) 
dcast(df, Person ~ Object, value.var="Value", fill = "0") 

# Person bike car motorcycle phone skateboard TV watch 
# 1  A 1 1   0  1   0 0  1 
# 2  B 0 1   0  0   1 0  0 
# 3  C 1 1   1  0   0 1  0 
> 
+0

太棒了! 'stringsAsfactors = FALSE'甚至解決了導入文件的問題(參見編輯)。謝謝 ! – user31888

0

我們可以使用tidyverse

library(tidyr) 
df %>% 
    spread(Object, Value, fill = 0) 
# Person bike car motorcycle phone skateboard TV watch 
#1  A 1 1   0  1   0 0  1 
#2  B 0 1   0  0   1 0  0 
#3  C 1 1   1  0   0 1  0 
相關問題