我想從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
你需要指定一個公式,包含'〜',否則,[R認爲你試圖把兩個數相加。也許'個人+對象〜.'? – neilfws
@neilfws:謝謝! 'dcast(df,Person〜。+ Object,variable.var =「Value」)'種類的作品。 – user31888
但是從文件導入相同的數據幀會返回不同的錯誤(請參閱上面的編輯) – user31888