问题描述:

I have a csv file that contains a data; TYPE and Area. I want to sort the data based on type and then add the area, after that i want to save that file in a csv/excel format.

The data looks like as follows;

TYPE Area

P 38304

P 14729

P 39342

R 652

R 497

C 4506

U 1705

U 1513

U 1514

U 1531

U 1580

U 1581

U 113509

U 13198

U 114730

U 12402

C 3252

I want to make the data as follows

P R U C

38304 652 1705 4506

14729 497 1513 3252

39342 1514

1531

1580

1581

113509

13198

114730

12402

And then Do the sum by column

P R U C

92375 1149 263263 7758

so far i have following codes;

 data=read.table("Book1.csv", header=TRUE, sep=',')

x=(sapply(split(data$Area, data$TYPE), sort))

write.csv(x, file="test.csv")

I tried to do the write csv first but due to unequal row i cannot write the csv. I am stuck, i know it is possible to add first and then write the final output but i am not able to do the coding.

Thanks Lira

网友答案:

I hope this works !

library(plyr)
newdata <- data[order(Type, Area),] 
data.new <- ddply(newdata, c("TYPE"), summarise, Area = sum("Area")) 
t.data   <- t(data.new)
write.csv(x, file="test.csv")
相关阅读:
Top