gpt4 book ai didi

r - Dplyr Mutate_each 用于成对的列集

转载 作者:行者123 更新时间:2023-12-02 08:21:04 24 4
gpt4 key购买 nike

有没有办法使用dplyr::mutate_each实现下面的转换?

data.frame(x1 = 1:5, x2 = 6:10, y1 = rnorm(5), y2 = rnorm(5)) %>%
mutate(diff1 = x1 - y1, diff2 = x2 - y2)

## x1 x2 y1 y2 diff1 diff2
## 1 1 6 1.03645018 -0.8602099 -0.03645018 6.860210
## 2 2 7 -1.10790835 1.6912875 3.10790835 5.308712
## 3 3 8 0.95452119 2.7232657 2.04547881 5.276734
## 4 4 9 0.01370762 1.6385765 3.98629238 7.361424
## 5 5 10 0.19354354 -1.0464360 4.80645646 11.046436

我意识到这是一个微不足道的示例,并且如我所描述的那样很容易完成,但我正在尝试使用更大的列集来完成类似的事情。

谢谢

最佳答案

正如@Gregor 在评论中提到的那样,如果您想使用dplyr,最好以整洁的格式获取您的数据。这是一个想法:

library(dplyr)
library(tidyr)

df %>%
add_rownames() %>%
gather(key, val, -rowname) %>%
separate(key, c("var", "num"), "(?<=[a-z]) ?(?=[0-9])") %>%
spread(var, val) %>%
mutate(diff = x - y)

给出:

#Source: local data frame [10 x 5]
#
# rowname num x y diff
# (chr) (chr) (dbl) (dbl) (dbl)
#1 1 1 1 1.03645018 -0.03645018
#2 1 2 6 -0.86020990 6.86020990
#3 2 1 2 -1.10790835 3.10790835
#4 2 2 7 1.69128750 5.30871250
#5 3 1 3 0.95452119 2.04547881
#6 3 2 8 2.72326570 5.27673430
#7 4 1 4 0.01370762 3.98629238
#8 4 2 9 1.63857650 7.36142350
#9 5 1 5 0.19354354 4.80645646
#10 5 2 10 -1.04643600 11.04643600

如果出于某种原因您在执行操作后仍然想要宽格式的数据,您可以添加到管道:

  gather(key, value, -(rowname:num)) %>%
unite(key_num, key, num, sep = "") %>%
spread(key_num, value)

这会给出:

#Source: local data frame [5 x 7]
#
# rowname diff1 diff2 x1 x2 y1 y2
# (chr) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)
#1 1 -0.03645018 6.860210 1 6 1.03645018 -0.8602099
#2 2 3.10790835 5.308713 2 7 -1.10790835 1.6912875
#3 3 2.04547881 5.276734 3 8 0.95452119 2.7232657
#4 4 3.98629238 7.361423 4 9 0.01370762 1.6385765
#5 5 4.80645646 11.046436 5 10 0.19354354 -1.0464360

数据

df <- structure(list(x1 = 1:5, x2 = 6:10, y1 = c(1.03645018, -1.10790835, 
0.95452119, 0.01370762, 0.19354354), y2 = c(-0.8602099, 1.6912875,
2.7232657, 1.6385765, -1.046436)), .Names = c("x1", "x2", "y1",
"y2"), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))

关于r - Dplyr Mutate_each 用于成对的列集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com