[R] apply transformation

santosh santosh.srinivas at gmail.com
Fri Jan 13 11:55:51 CET 2012


Hello All,

I have the following dataset:

    Year   2006   2007
Jan  Jan 0.0204 0.0065
Feb  Feb 0.0145 0.0082
Mar  Mar 0.0027 0.0122


> dput(d_tmp)
structure(list(Year = c("Jan", "Feb", "Mar"), `2006` = c(0.0204,
0.0145, 0.0027), `2007` = c(0.0065, 0.0082, 0.0122)), .Names =
c("Year",
"2006", "2007"), row.names = c("Jan", "Feb", "Mar"), class =
"data.frame")


I am trying to use the apply function but the values seem to be
getting coerced to characters. I could recast in my function ... but I
suspect there should be an easier way.

I can always use a for loop to get the output I need but just
wondering if there a way to get the same using apply or some other
function ... (the number of years can be changing in my requirement)

My final output needs to be as follows:

Year	2006	2006-Lbl	2007	2007-Lbl
Jan	0.0204	'2.04%'	0.0065	'0.65%'
Feb	0.0145	'1.45%'	0.0082	'0.82%'
Mar	0.0027	'0.27%'	0.0122	'1.22%'

i.e.
> dput(d_final)
structure(list(Year = structure(c(2L, 1L, 3L), .Label = c("Feb",
"Jan", "Mar"), class = "factor"), X2006 = c(0.0204, 0.0145, 0.0027
), X2006.Lbl = structure(c(3L, 2L, 1L), .Label = c("'0.27%'",
"'1.45%'", "'2.04%'"), class = "factor"), X2007 = c(0.0065, 0.0082,
0.0122), X2007.Lbl = structure(1:3, .Label = c("'0.65%'", "'0.82%'",
"'1.22%'"), class = "factor")), .Names = c("Year", "X2006",
"X2006.Lbl",
"X2007", "X2007.Lbl"), row.names = c(NA, -3L), class = "data.frame")

Please advise.

Santosh



More information about the R-help mailing list