[R] how can I convert a long to wide matrix?

Marna Wagley m@rn@@w@gley @ending from gm@il@com
Wed May 2 00:24:06 CEST 2018


Hi R user,
I was trying to convert a long matrix to wide? I have an example and would
like to get a table (FinalData1):


FinalData1
         B1    B2
id_X   "A"   "B"
id_Y   "A"   "B"

but I got the following table using the following code.

FinalData1

     B1  B2

id_X "A" "A"

id_Y "A" "B"


the code and the example data I used are given below. Is there any
suggestions to fix the problem?


dat<-structure(list(ID = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("id_X",


"id_Y"), class = "factor"), EventDate = structure(c(4L, 5L, 2L,

3L, 1L), .Label = c("9/15/16", "9/15/17", "9/7/16", "9/8/16",

"9/9/16"), class = "factor"), timeGroup = structure(c(1L, 1L,

2L, 1L, 2L), .Label = c("B1", "B2"), class = "factor"), SITE = structure(c(
1L,

1L, 2L, 1L, 2L), .Label = c("A", "B"), class = "factor")), .Names = c("ID",

"EventDate", "timeGroup", "SITE"), class = "data.frame", row.names = c(NA,

-5L))


tmp <- split(dat, dat$ID)

tmp1 <- do.call(rbind, lapply(tmp, function(dat){

tb <- table(dat$timeGroup)

idx <- which(tb>0)

tb1 <- replace(tb, idx, as.character(dat$SITE))

}))


tmp1

FinalData<-print(tmp1, quote=FALSE)

	[[alternative HTML version deleted]]




More information about the R-help mailing list