Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何基于列创建成对表,以便在r中的元素之间进行分割_R - Fatal编程技术网

如何基于列创建成对表,以便在r中的元素之间进行分割

如何基于列创建成对表,以便在r中的元素之间进行分割,r,R,我想要在列%中的元素之间进行两两分割的数据帧(d) > d x % a 3 b 10 c 5 我想两两做这个 3 |5 |10 a 3 |1 |0.6 |0.3 b 5 |1.7|1 |2 c 10|3.3|2 |1 谢谢。我们可以使用outer outer(d$`%`, d$`%`, `/`) 我们可以向其中添加行和列名 matrix(outer(d$`%`, d$`%`, `/`), nrow(d), dimnames = list(d$`%`, d$

我想要在列%中的元素之间进行两两分割的数据帧(d)

> d

x %
a 3
b 10
c 5
我想两两做这个

     3  |5   |10
a 3 |1  |0.6 |0.3
b 5 |1.7|1   |2
c 10|3.3|2   |1

谢谢。

我们可以使用
outer

outer(d$`%`, d$`%`, `/`)
我们可以向其中添加行和列名

matrix(outer(d$`%`, d$`%`, `/`), nrow(d), dimnames = list(d$`%`, d$`%`))

#      3  10   5
#3  1.00 0.3 0.6
#10 3.33 1.0 2.0
#5  1.67 0.5 1.0
数据

d <- structure(list(x = structure(1:3, .Label = c("a", "b", "c"), class = "factor"),
`%` = c(3L, 10L, 5L)), class = "data.frame", row.names = c(NA, -3L))

d我们可以使用
outer

outer(d$`%`, d$`%`, `/`)
我们可以向其中添加行和列名

matrix(outer(d$`%`, d$`%`, `/`), nrow(d), dimnames = list(d$`%`, d$`%`))

#      3  10   5
#3  1.00 0.3 0.6
#10 3.33 1.0 2.0
#5  1.67 0.5 1.0
数据

d <- structure(list(x = structure(1:3, .Label = c("a", "b", "c"), class = "factor"),
`%` = c(3L, 10L, 5L)), class = "data.frame", row.names = c(NA, -3L))

d我们可以使用
tidyverse
函数

library(tibble)
library(dplyr)
library(tidyr)
expand(d, col1 = `%`, col2 = `%`) %>% 
     mutate(new = col1/col2) %>%
     pivot_wider(names_from = col2, values_from = new) %>% 
     column_to_rownames('col1')
#         3   5  10
#3  1.000000 0.6 0.3
#5  1.666667 1.0 0.5
#10 3.333333 2.0 1.0
数据
d我们可以使用
tidyverse
函数

library(tibble)
library(dplyr)
library(tidyr)
expand(d, col1 = `%`, col2 = `%`) %>% 
     mutate(new = col1/col2) %>%
     pivot_wider(names_from = col2, values_from = new) %>% 
     column_to_rownames('col1')
#         3   5  10
#3  1.000000 0.6 0.3
#5  1.666667 1.0 0.5
#10 3.333333 2.0 1.0
数据
d