How do I get two lists together in R?
I am generating two tables using the table
command in R
. I want to make a table/dataframe/matrix such that all the names from 开发者_C百科both the tables are represented and proper 'zero' counts are included in the output. e.g.
The data I currently have looks something as follows
Table 1
A B C
1 2 4
Table 2
C D E
3 4 4
I would like to have output that is as follows:
Table1 Table2
A 1 0
B 2 0
C 4 3
D 0 4
E 0 4
How can I do this in R?
without reshape:
t1 <- table(c("A", rep("B", 2), rep("C", 4)))
t2 <- table(c(rep("C", 3), rep("D", 4), rep("E", 4)))
ndf <- merge(t1, t2, by = "Var1", all = TRUE)
ndf[is.na(ndf)] <- 0
ndf
Var1 Freq.x Freq.y
1 A 1 0
2 B 2 0
3 C 4 3
4 D 0 4
5 E 0 4
Ignoring what I think is a typo in your question (the C frequencies should be 4 and 3, right, not 2 and 3?) you can do this by coercing to data frames and then merging:
t1 <- table(rep(LETTERS[1:3],times=c(1,2,4)))
t2 <- table(rep(c("C","D",'E'),times=c(3,4,4)))
merge(as.data.frame(t1),as.data.frame(t2),by="Var1",all=T)
and then converting the NAs to zeros.
DATA
dat <- list(rep(LETTERS[1:3],times=c(1,2,4)),rep(LETTERS[3:5],times=c(3,2,2)))
CODE
f <- function(d){
lev <- unique(unlist(d, use.names=FALSE))
d <- lapply(d, factor, levels=lev)
r <- do.call(cbind, lapply(d, table))
colnames(r) <- paste("Table", seq(NCOL(r)), sep="")
return(r)
}
OUTPUT
f(dat)
Table1 Table2
A 1 0
B 2 0
C 4 3
D 0 2
E 0 2
精彩评论