这是初始数据。
temp <- structure(list(Initial = c(
32.5, 30.4, 36.5, 4.2, 24.3
), Amount = c(
374.24, 79.05, 1.02, 0.79, 0.71
), Load = c(
11.512, 2.605, 0.027, 0.021, 0.019
), Extra = c(
36.9, 32.5, 12.2, 12.2, 12.2
), Perc = c(
114L, 107L, 33L, 33L, 33L
)), row.names = c(
1L, 2L, 3L, 4L, 5L
), class = "data.frame")
这就是我要创建的。我希望使用整洁的方式。
data <- structure(list(Rs = c(
"Initial", "Initial", "Initial", "Initial",
"Initial", "Initial", "Initial", "Initial", "Initial", "Initial",
"Initial", "Initial", "Initial", "Initial", "Initial", "Initial",
"Initial", "Initial", "Initial", "Initial", "Amount", "Amount",
"Amount", "Amount", "Amount", "Amount", "Amount", "Amount", "Amount",
"Amount", "Amount", "Amount", "Amount", "Amount", "Amount", "Load",
"Load", "Load", "Load", "Load", "Load", "Load", "Load", "Load",
"Load", "Extra", "Extra", "Extra", "Extra", "Extra"
), Rvalue = c(
32.5,
30.4, 36.5, 4.2, 24.3, 32.5, 30.4, 36.5, 4.2, 24.3, 32.5, 30.4,
36.5, 4.2, 24.3, 32.5, 30.4, 36.5, 4.2, 24.3, 374.24, 79.05,
1.02, 0.79, 0.71, 374.24, 79.05, 1.02, 0.79, 0.71, 374.24, 79.05,
1.02, 0.79, 0.71, 11.512, 2.605, 0.027, 0.021, 0.019, 11.512,
2.605, 0.027, 0.021, 0.019, 36.9, 32.5, 12.2, 12.2, 12.2
), Cs = c(
"Amount",
"Amount", "Amount", "Amount", "Amount", "Load", "Load", "Load",
"Load", "Load", "Extra", "Extra", "Extra", "Extra", "Extra",
"Perc", "Perc", "Perc", "Perc", "Perc", "Load", "Load", "Load",
"Load", "Load", "Extra", "Extra", "Extra", "Extra", "Extra",
"Perc", "Perc", "Perc", "Perc", "Perc", "Extra", "Extra", "Extra",
"Extra", "Extra", "Perc", "Perc", "Perc", "Perc", "Perc", "Perc",
"Perc", "Perc", "Perc", "Perc"
), Cvalue = c(
374.24, 79.05, 1.02,
0.79, 0.71, 11.512, 2.605, 0.027, 0.021, 0.019, 36.9, 32.5, 12.2,
12.2, 12.2, 114, 107, 33, 33, 33, 11.512, 2.605, 0.027, 0.021,
0.019, 36.9, 32.5, 12.2, 12.2, 12.2, 114, 107, 33, 33, 33, 36.9,
32.5, 12.2, 12.2, 12.2, 114, 107, 33, 33, 33, 114, 107, 33, 33,
33
)), class = "data.frame", row.names = c(NA, -50L))
答案 0 :(得分:1)
pmap
的作用说明:
pmap(list(x, y, z), fun)
与Map(fun, x, y, z)
相同。然后pmap_dfr
做同样的事情,但另外rbind
将结果列表的所有元素一起放入一个数据帧。
library(tidyverse)
pairs <- expand.grid(names(temp), names(temp), stringsAsFactors = F) %>%
filter(Var1 > Var2)
pmap_dfr(pairs, ~{
tibble(Rs = .y, Rvalue = temp[[.y]],
Cs = .x, Cvalue = temp[[.x]])
})
edit:实际上,目前尚不清楚您如何确定要包括的Rs
,Cs
对,而不是。无论采用哪种逻辑,从expand.grid
开始并进行过滤都应该可以帮助您到达目的地。
答案 1 :(得分:1)
我们可以依次使用names(temp)
,select
所需的列然后gather
进行循环,最后将所有数据帧绑定在一起
library(tidyverse)
#head(names(temp),-1)
map_dfr(names(temp)[-length(temp)], ~select(temp,.x:ncol(temp)) %>%
gather(key = Cs,value = Cvalue,-.x) %>% mutate(Rs=.x) %>%
select(Rs,Rvalue=.x,everything()))