I want to transpose data sets similar to my.data below and then sum the rows.
my.data <- "landuse units year county.a county.b county.c county.d
apple acres 2010 0 2 4 6
pear acres 2010 10 20 30 40
peach acres 2010 500 400 300 200"
my.data2 <- read.table(textConnection(my.data), header = T)
my.data2
The desired output is:
counties all.fruit
county.a 510
county.b 422
county.c 334
county.d 246
I can do this with the code below. However, the following code seems like it must be enormous overkill. I am hoping there is a much simpler solution.
# transpose the data set
tmy.data2 <- t(my.data2)
tmy.data2 <- as.data.frame(tmy.data2)
# assign row names to the data set
my.rows <- row.names(tmy.data2)
transposed.data <- cbind(my.rows, tmy.data2)
transposed.data
# extract numbers to obtain row sums
fruit.data <- as.data.frame(transposed.data[4:dim(transposed.data)[1], 2:dim(transposed.data)[2]])
fruit.data2 <- as.matrix(fruit.data)
fruit.data3 <- matrix(as.numeric(fruit.data2), nrow=( dim(fruit.data2)[1] ), byrow=F)
# sum fruit by county
all.fruit <- rowSums(fruit.data3, na.rm=T)
# create row names for summed fruit data
counties <- my.rows[4:length(my.rows)]
almost.final.data <- cbind(counties, all.fruit)
really.final.data <- as.data.frame(almost.final.data)
really.final.data[,2] <- as.numeric(as.character(really.final.data[,2]))
really.final.data
str(really.final.data)
Thank you for any suggestions. I can use the code above, but view this request as an opportunity to greatly improve my programming.
I would just subset the
"county"columns, sum them, and create a data.frame using the results: