2017-06-23 9 views
0

私はこの特定の問題が以前フォーラムに出たとは思わないが、重複した質問の場合は正しい方向に向けるようにしてください!長い行と長い行の名前

私は以下のデータセットを持っており、それを長いものから広いものに変えたいと思います。

ID variable     value 
1 number of students   1000 
1 percentage on financial aid 28 
1 acceptance rate    12 
1 percentage on financial aid 35 
2 number of students   2000 
2 percentage on financial aid 1 
2 percentage on financial aid 70 

percentage on financial aidはIDごとに2回出現していることに注意してください。最初の出現は「財政援助」尺度による学校のランクであり、第2の出現は実際の値であるため、長い出現から広い出題に変わるときには、第2の出現を維持したいと考えています。

変数名percentage on financial aidは両方の値がまったく同じなので、最初のオカレンスを2番目のオカレンスで上書きするようにRに指示する方法があるかどうかは疑問でした。今はRが最初の出来事を残しているようです。

+0

は、あなただけのDUPのための最後のappearenceを取りたいです。最初にフィルタリングするのはなぜですか? – mt1022

+0

'最初に起こったこと'あなたはランダムな権利を意味しますか? – amonk

+0

ああ、あなたは正しい@ mt1022です。私はLAST = TRUEからやり直すことができないことを忘れ、2番目のインスタンスを保持しています。ありがとう、トン! – gonnastop

答えて

0
zz = ' 
ID variable     value 
1 number_of_students   1000 
1 percentage_on_financial_aid 28 
1 acceptance_rate    12 
1 percentage_on_financial_aid 35 
2 number_of_students   2000 
2 percentage_on_financial_aid 1 
2 percentage_on_financial_aid 70 
' 

df <- read.table(text = zz, header = TRUE) 


ndf = apply(df, 2, rev) 
ndf = as.data.frame(ndf) 
nd = reshape(ndf, idvar = "ID", timevar = "variable", direction = "wide") 
a = colnames(nd) 
b = sub('.*\\.', '', a) 
colnames(nd) = b 
nd 

    ID percentage_on_financial_aid number_of_students acceptance_rate 
1 2       70    2000   <NA> 
4 1       35    1000    12 

あなたがfromLast = T行う場合:

nd = reshape(df, idvar = "ID", timevar = "variable", direction = "wide") 
a = colnames(nd) 
b = sub('.*\\.', '', a) 
colnames(nd) = b 
nd 
0

を私はコメントし、人々のおかげで、これを考え出しました。

ソリューション:あなたが言ったように

df <- subset(df,duplicated(df[,1:2])|!duplicated(df[,1:2],fromLast=TRUE))

関連する問題