如何将一行的百分比连接到一个值中?
How to concatenate the percentage of a row in a single value?
我想连接单行中该值的百分比。假设我有:
dat<-data.frame(x1=c(1), x2=c(4), x3=c(5), stringsAsFactors = FALSE)
我想在 dat$concat
列中有一个连接值,如下所示:[10,40,50](现在每个值都是百分比)
我之前问过如何连接,命令运行良好:
dat$conc <- paste0("[",apply(dat,1,paste,collapse=","),"]")
我该怎么做?
如果我们假设 5 代表 50%,那么它就像用 dat*.1 替换 dat 一样简单,就像这样:
dat <- data.frame(x1=c(1), x2=c(4), x3=c(5), stringsAsFactors = FALSE)
dat$conc <- paste0("[",apply(dat*.1,1,paste,collapse=","),"]")
x1 x2 x3 conc
1 1 4 5 [0.1,0.4,0.5]
但我确实要注意,如果 5 表示 5%,而不是 50%,那么您需要将 dat 替换为 dat/100,如下所示:
dat <- data.frame(x1=c(1), x2=c(4), x3=c(5), stringsAsFactors = FALSE)
dat$conc <- paste0("[",apply(dat/100,1,paste,collapse=","),"]")
x1 x2 x3 conc
1 1 4 5 [0.01,0.04,0.05]
编辑:
要获取每个值相对于其行的百分比(即 value/rowSums(x)),试试这个:
dat <- data.frame(x1=c(7),x2=c(4),x3=c(5),stringsAsFactors=FALSE)
dat$conc <- paste0("[",apply(dat/rowSums(dat),1,paste,collapse=","),"]")
输出:
x1 x2 x3 conc
1 7 4 5 [0.4375,0.25,0.3125]
我想连接单行中该值的百分比。假设我有:
dat<-data.frame(x1=c(1), x2=c(4), x3=c(5), stringsAsFactors = FALSE)
我想在 dat$concat
列中有一个连接值,如下所示:[10,40,50](现在每个值都是百分比)
我之前问过如何连接,命令运行良好:
dat$conc <- paste0("[",apply(dat,1,paste,collapse=","),"]")
我该怎么做?
如果我们假设 5 代表 50%,那么它就像用 dat*.1 替换 dat 一样简单,就像这样:
dat <- data.frame(x1=c(1), x2=c(4), x3=c(5), stringsAsFactors = FALSE)
dat$conc <- paste0("[",apply(dat*.1,1,paste,collapse=","),"]")
x1 x2 x3 conc
1 1 4 5 [0.1,0.4,0.5]
但我确实要注意,如果 5 表示 5%,而不是 50%,那么您需要将 dat 替换为 dat/100,如下所示:
dat <- data.frame(x1=c(1), x2=c(4), x3=c(5), stringsAsFactors = FALSE)
dat$conc <- paste0("[",apply(dat/100,1,paste,collapse=","),"]")
x1 x2 x3 conc
1 1 4 5 [0.01,0.04,0.05]
编辑:
要获取每个值相对于其行的百分比(即 value/rowSums(x)),试试这个:
dat <- data.frame(x1=c(7),x2=c(4),x3=c(5),stringsAsFactors=FALSE)
dat$conc <- paste0("[",apply(dat/rowSums(dat),1,paste,collapse=","),"]")
输出:
x1 x2 x3 conc
1 7 4 5 [0.4375,0.25,0.3125]