r - 使用 tidyr 在多个键列中收集多个列 [英] r - gather multiple columns in multiple key columns with tidyr

查看:24
本文介绍了r - 使用 tidyr 在多个键列中收集多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定 tidyr::gather 是否可以用于获取多个列并将它们合并到多个关键列中.

Not sure if tidyr::gather can be used to take multiple columns and merge them in multiple key columns.

有人问过类似的问题,但它们都是指在一个关键列中收集多个列.

Similar questions have been asked but they all refer to gathering multiple columns in one key column.

我正在尝试将 4 列收集到 2 个键和 2 个值列中,如下例所示:

I'm trying to gather 4 columns into 2 key and 2 value columns like in the following example:

示例数据:

df <- data.frame(
    subject = c("a", "b"),
    age1 = c(33, 35),
    age2 = c(43, 45),
    weight1 = c(90, 67),
    weight2 = c(70, 87)
)

  subject age1 age2 weight1 weight2
1       a   33   43      90      70
2       b   35   45      67      87

想要的结果:

dfe <- data.frame(
    subject = c("a", "a", "b", "b"),
    age = c("age1", "age2", "age1", "age2"),
    age_values = c(33, 43, 35, 45),
    weight = c("weight1", "weight2", "weight1", "weight2"),
    weight_values = c(90, 70, 67, 87)
)

  subject  age age_values  weight weight_values
1       a age1         33 weight1            90
2       a age2         43 weight2            70
3       b age1         35 weight1            67
4       b age2         45 weight2            87

推荐答案

这是一种方法 -

df %>%
  gather(key = "age", value = "age_values", age1, age2) %>%
  gather(key = "weight", value = "weight_values", weight1, weight2) %>%
  filter(substring(age, 4) == substring(weight, 7))

  subject  age age_values  weight weight_values
1       a age1         33 weight1            90
2       b age1         35 weight1            67
3       a age2         43 weight2            70
4       b age2         45 weight2            87

这篇关于r - 使用 tidyr 在多个键列中收集多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆