Skip to content

MACRO-LOOP in R

2 messages · Amoy Yang, Jeff Newmiller

#
I am doing the data transpose with rename as shown below (step1 ~ step4)
1. Is any way?in R similar to PROC?TRANSPOSE used in SAS?2. How to use MACRO-LOOP to simplify the following procedure?
THANK YOU?FOR?HELPS!
# create data for test
x<-data.frame(
?a=c(1,2,3),
?b=c("1","2","3")); 
x; str(x)# step1: parse out to 3 tabs
x1<-x[x$a == 1,]; x1
x2<-x[x$a == 2,]; x2
x3<-x[x$a == 3,]; x3# step2: remove column a in each tab
x1$a<-NULL; x1
x2$a<-NULL; x2
x3$a<-NULL; x3# step3: rename column b to b1, b2 and b3 by y1, y2 and y3
names(x1)[names(x1)=="b"]<-"b_1"; x1
names(x2)[names(x2)=="b"]<-"b_2"; x2
names(x3)[names(x3)=="b"]<-"b_3"; x3# setp4: set x1, x3 and x3 together
x123=cbind(x1,x2,x3); x123
#
What a mess. Transposing factors is highly unlikely to lead to sensible results. Did you look at str( x123 ) as your example created it? 

x <- data.frame( a=c(1,2,3), b=c("1","2","3"), stringsAsFactors=FALSE )

x123new <- setNames( as.data.frame( t( x[ , "b" ] ) ), paste( "b", 1:3, sep="_" ) )

R is not SAS. Please read the Introduction to R document (again). Pay attention to the discussions of indexing, character mode and factors.