R Program Vector, record Column Percent

53 views Asked by At

This is my vector

head(sep)

enter image description here

I must find percent of all SEP 11 in each row.

For instance, in first row, percent of SEP 11 is

100 * ((63 + 124)/ (63 + 124 + 0 + 0))

And would like this stored in newly created 8th column

Thanks

dput

> dput(head(sep))
structure(list(Site = structure(1:6, .Label = c("31R001", "31R002", 
"31R003", "31R004", "31R005", "31R006", "31R007", "31R008", "31R011", 
"31R013", "31R014", "31R016", "31R018", "31R019", "31R020", "31R021", 
"31R022", "31R023", "31R024", "31R025", "31R026", "31R027", "31R029", 
"31R030", "31R031", "31R032", "31R034", "31R035", "31R036", "31R038", 
"31R039", "31R040", "31R041", "31R042", "31R043", "31R044", "31R045", 
"31R046", "31R048", "31R049", "31R050", "31R051", "31R052", "31R053", 
"31R054", "31R055", "31R056", "31R057", "31R058", "31R059", "31R060", 
"31R061", "31R069", "31R071", "31R072", "31R075", "31R435", "31R440", 
"31R445", "31R450", "31R455", "31R460", "31R470", "31R600", "31R722", 
"31R801", "31R825", "31R826", "31R829", "31R840", "31R843", "31R861", 
"31R880"), class = "factor"), Latitude = c(33.808874, 33.877256, 
33.820825, 33.852373, 33.829697, 33.810274), Longitude = c(-117.844048, 
-117.700135, -117.811845, -117.795516, -117.787532, -117.830429
), Windows.SEP.11 = c(63L, 174L, 11L, 85L, 163L, 71L), Mac.SEP.11 = c(0L, 
1L, 4L, 0L, 0L, 50L), Windows.SEP.12 = c(124L, 185L, 9L, 75L, 
23L, 5L), Mac.SEP.12 = c(0L, 1L, 32L, 1L, 0L, 50L)), .Names = c("Site", 
"Latitude", "Longitude", "Windows.SEP.11", "Mac.SEP.11", "Windows.SEP.12", 
"Mac.SEP.12"), row.names = c(NA, 6L), class = "data.frame")
1

There are 1 answers

0
akrun On BEST ANSWER

Assuming that you want to get the rowSums of columns that have 'Windows' as column names, we subset the dataset ("sep1") using grep. Then get the rowSums(Sub1), divide by the rowSums of all the numeric columns (sep1[4:7]), multiply by 100, and assign the results to a new column ("newCol")

 Sub1 <- sep1[grep("Windows", names(sep1))]
 sep1$newCol <- 100*rowSums(Sub1)/rowSums(sep1[4:7])