[R] new column that applies function to all rows based on last row
arun
smartpink111 at yahoo.com
Mon Mar 3 18:03:16 CET 2014
HI BNC,
For the example you provided:
CHAR1n_totalNew <- within(CHAR1n_total,Newvar <- (Freq/tail(Freq,1))*100)
#If you have more than one column
#For example
set.seed(42)
Freq2 <- sample(4,10,replace=TRUE)
CHAR1n_total$Freq2 <- c(Freq2,sum(Freq2))
dat2 <- as.data.frame(matrix(NA,ncol=((ncol(CHAR1n_total)-1)*2)+1,nrow=nrow(CHAR1n_total)))
dat2[,1] <- CHAR1n_total[,1]
dat2[,seq(2,ncol(dat2),by=2)] <- CHAR1n_total[,-1]
dat2[,seq(3,ncol(dat2),by=2)] <- t((t(CHAR1n_total[,-1])/unlist(tail(CHAR1n_total[,-1],1)))*100)
dat2
##You can change the names of the columns accordingly.
A.K.
I know this is a simple question, but I am having trouble generating
output without errors. I want to create a column containing values for
each row that are generated by dividing another column's row value by
the same column's sum (last-row value):
Here is the (less-than-elegant) practice script I'm working with (minus the code generating errors):
mydata <- data.frame (CaseID = c("1","2","3","4","5","6","7","8","9","10","11","12","13","14"),
EstablishmentEEs = c(3,3,4,5,8,8,9,10,10,11,12,12,13,14))
freqdata.1n <- mydata$EstablishmentEEs
CHAR1n <- table(freqdata.1n)
CHAR1nmatrix <- as.data.frame(CHAR1n)
rownames(CHAR1nmatrix) <- CHAR1nmatrix$freqdata.1n
CHAR1n_total <- addmargins(as.table(as.matrix(CHAR1nmatrix[-1])), 1)
CHAR1n_total <- as.data.frame(CHAR1n_total)
CHAR1n_total <- subset(CHAR1n_total, select= -Var2)
library(gdata)
CHAR1n_total <- rename.vars(CHAR1n_total,from="Var1",to="freqdata.1n",info=FALSE)
Thanks for your patience!
More information about the R-help
mailing list