[R] R dataframe question

arun smartpink111 at yahoo.com
Sun Jan 26 01:54:34 CET 2014


Hi,
dat1 <- read.table(text="X1
1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3",sep="",header=TRUE)

 dat2 <- setNames(as.data.frame(matrix(dat1[,1],3,3)),paste0("X",1:3))

str(dat2)
#'data.frame':    3 obs. of  3 variables:
# $ X1: Factor w/ 3 levels "1,1","1,2","1,3": 1 2 3
# $ X2: Factor w/ 3 levels "2,1","2,2","2,3": 1 2 3
# $ X3: Factor w/ 3 levels "3,1","3,2","3,3": 1 2 3


dat2New <- setNames(as.data.frame(matrix(dat1[,1],3,3),stringsAsFactors=FALSE),paste0("X",1:3)) #
 str(dat2New)
#'data.frame':    3 obs. of  3 variables:
# $ X1: chr  "1,1" "1,2" "1,3"
# $ X2: chr  "2,1" "2,2" "2,3"
# $ X3: chr  "3,1" "3,2" "3,3"
A.K.


Hello, 

For example, my data is in this format (with header): 

X1 
1,1 
1,2 
1,3 
2,1 
2,2 
2,3 
3,1 
3,2 
3,3 

But I would like for it to be in this format: 
X1    X2    X3 
1,1   2,1   3,1 
1,2   2,2   3,2 
1,3   2,3   3,3 

I hope this helps make my question clearer.  Thank you for your quick reply.   

M 


On Saturday, January 25, 2014 7:16 PM, arun <smartpink111 at yahoo.com> wrote:
Hi,

The question is not clear.

set.seed(45)
 spe <- data.frame(Col1=sample(c(1:10,letters[1:2]),400,replace=TRUE))
 mat1 <- matrix(spe[,1],nrow=20,ncol=20)



#If you want to replace the non-numeric values with NAs,
 mat2 <- matrix(as.numeric(as.character(spe[,1])),nrow=20,ncol=20)


A.K.



Hello, 

My data is in a 1 column x 40000 row data frame.  I would like 
to make it a 200 column x 200 row data frame. When I was using all 
numeric values, I used the code below to transform my vector into a 
matrix.   

spematrix=data.matrix(spe) 
matrix = matrix(spe, nrow = 200, ncol=200) 

I cannot use this now though because my data contains non-numeric values.   

I am new to R and would appreciate any help.   

Thanks, 

Mary  




More information about the R-help mailing list