逐个单元地连接两个矩阵或数据帧(concatenate two matrices or dataframes cell-by-cell)
我想连接df和p ,如我的MRE的最后一步所示。 有任何想法吗?
# functions ---- asterisk <- function(y) symnum(y, c(0, .001, .01, .05, .1, 1), c("***", "**", "*", ".", " ")) rd2 <- function(y) sprintf("%.2f", round(y, 2)) # packages ---- require(foreign) require(nnet) # example data from http://www.ats.ucla.edu/stat/r/dae/mlogit.htm ml <- read.dta("http://www.ats.ucla.edu/stat/data/hsbdemo.dta") ml$prog2 <- relevel(ml$prog, ref = "academic") test <- multinom(prog2 ~ ses + write, data = ml) # get coefficients and round df <- data.frame(coefficients(test)) df <- as.data.frame(lapply(df, rd2)) row.names(df) <- row.names(coefficients(test)) df # X.Intercept. sesmiddle seshigh write # general 2.85 -0.53 -1.16 -0.06 # vocation 5.22 0.29 -0.98 -0.11 # get p-values z <- summary(test)$coefficients/summary(test)$standard.errors p <- matrix((1 - pnorm(abs(z), 0, 1)) * 2, nrow=nrow(z)) p <- as.data.frame(apply(p, c(1,2), asterisk)) # V1 V2 V3 V4 # 1 * * ** # 2 *** . *** # concatenate df and p # X.Intercept. sesmiddle seshigh write # general 2.85* -0.53 -1.16* -0.06** # vocation 5.22*** 0.29 -0.98. -0.11***I want to concatenate df and p as shown in the last step of my MRE. Any ideas?
# functions ---- asterisk <- function(y) symnum(y, c(0, .001, .01, .05, .1, 1), c("***", "**", "*", ".", " ")) rd2 <- function(y) sprintf("%.2f", round(y, 2)) # packages ---- require(foreign) require(nnet) # example data from http://www.ats.ucla.edu/stat/r/dae/mlogit.htm ml <- read.dta("http://www.ats.ucla.edu/stat/data/hsbdemo.dta") ml$prog2 <- relevel(ml$prog, ref = "academic") test <- multinom(prog2 ~ ses + write, data = ml) # get coefficients and round df <- data.frame(coefficients(test)) df <- as.data.frame(lapply(df, rd2)) row.names(df) <- row.names(coefficients(test)) df # X.Intercept. sesmiddle seshigh write # general 2.85 -0.53 -1.16 -0.06 # vocation 5.22 0.29 -0.98 -0.11 # get p-values z <- summary(test)$coefficients/summary(test)$standard.errors p <- matrix((1 - pnorm(abs(z), 0, 1)) * 2, nrow=nrow(z)) p <- as.data.frame(apply(p, c(1,2), asterisk)) # V1 V2 V3 V4 # 1 * * ** # 2 *** . *** # concatenate df and p # X.Intercept. sesmiddle seshigh write # general 2.85* -0.53 -1.16* -0.06** # vocation 5.22*** 0.29 -0.98. -0.11***最满意答案
如果您不介意用连接的数据覆盖现有的df :
df[] <- lapply(1:ncol(df), function(col) paste0(df[,col],p[,col]) );如果没有,你可以从df分配一个新的变量(比如dfp )并赋值。
使用原始df作为此任务的起点非常有用,因为它可以避免担心设置/修复维名称。
If you don't mind overwriting the existing df with the concatenated data:
df[] <- lapply(1:ncol(df), function(col) paste0(df[,col],p[,col]) );If not, you can assign a new variable from df (say dfp) and assign that.
Using the original df as a starting point for this task is useful because it prevents having to worry about setting/fixing dimension names.
更多推荐
发布评论