r - how to split columns by certain category? -


my data this:

  dd gg site   5  10   7  8    5  6  b    7  9  b  

i want split column of site according a , b.desired output is:

    dd gg site  gg_b     5  10     6     7  8      9 

your request seems strange in way values site treated differently b values.

using data:

xx = structure(list(dd = c(5l, 7l, 5l, 7l), gg = c(10l, 8l, 6l, 9l ), site = structure(c(1l, 1l, 2l, 2l), .label = c("a", "b"), class = "factor")), .names = c("dd",  "gg", "site"), class = "data.frame", row.names = c(na, -4l)) 

we can "spread" columns long wide format using tidyr::spread. eliminates site column , treats , b values of same:

library(tidyr) (xx = spread(xx, key = site, value = gg)) #   dd  b # 1  5 10 6 # 2  7  8 9 

adding gg_ prefix names:

names(xx)[2:3] = paste("gg", names(xx[2:3]), sep = "_") xx #   dd gg_a gg_b # 1  5   10    6 # 2  7    8    9 

i prefer data in above format. if want match desired output, adding xx$site = "a" , renaming existing columns easy enough.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -