【问题标题】:how can i create new variable which will add the values of columns conditional on other set of variables ? (Example provided)我如何创建新变量,它将添加以其他变量集为条件的列的值? (提供示例)
【发布时间】:2020-12-03 02:55:23
【问题描述】:

我有四个变量用于家庭成员年龄,age_01、age_02、age_03 和 age_04,还有四个变量用于他们的工作时间、work_hr_01、work_hr_02、work_hr_03 和 work_hr_04。我想为 16 岁和 17 岁家庭成员的总工作时间创建新变量。我有以下数据:

id   age_01 age_02 age_03 age_04 work_hr_01 work_hr_02 work_hr_03 work_hr_04  
 1     24      16      22     16      33         45         55        40
 2     33      17      18     17      40         33         35        39         
 3     33      17      16     16      40         33         34        42

具有两个新变量 work_hr_by_16 和 work_hr_by_17 的期望结果

ID age_01 age_02 age_03 age_04 work_hr_01 work_hr_02 work_hr_03 work_hr_04  work_hr_by_16   work_hr_by_17
1    24      16      22     16      33         45         55        40              85            na
2    33      17      18     17      40         33         35        39              na            72
3    33      17      16     16      40         33         34        42              76            33

【问题讨论】:

  • 请以可复制的形式发布数据。运行 dput(yourdata) 并将结果粘贴到原始问题中。此外,您的示例是添加 work_hr_01work_hr_04 以获得 73 作为预期答案的第一行。这不应该是work_hr_02work_hr_04 的总和为 85 吗?
  • 是的,应该是 85,谢谢。我编辑了。因为我是新手,所以我不完全确定如何制作可复制的表格。这是一个巨大的数据集,我做了一个例子。

标签: r dataframe if-statement variables dplyr


【解决方案1】:

如果您以长格式获取数据,其中包含不同的年龄和工作时间列,则管理数据会容易得多。然后我们可以filter 并仅选择那些age 为16 或17 的行,sum 他们的work_hr 并以宽格式取回数据。

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -id, 
               names_to = c('.value', 'num'), 
               names_pattern = '(.*)_(.*)') %>%
  filter(age %in% 16:17) %>%
  group_by(id, age) %>%
  summarise(work_hr = sum(work_hr)) %>%
  pivot_wider(names_from = age, values_from = work_hr, 
              names_prefix = 'work_hr_by_') %>%
  left_join(df, by = 'id')

#    id  work_hr_by_16 work_hr_by_17 age_01 age_02 age_03 age_04 ... 
#  <int>         <int>         <int>  <int>  <int>  <int>  <int> ...
#1     1            85            NA     24     16     22     16 ...
#2     2            NA            72     33     17     18     17 ...
#3     3            76            33     33     17     16     16 ...

数据

df <- structure(list(id = 1:3, age_01 = c(24L, 33L, 33L), age_02 = c(16L, 
17L, 17L), age_03 = c(22L, 18L, 16L), age_04 = c(16L, 17L, 16L
), work_hr_01 = c(33L, 40L, 40L), work_hr_02 = c(45L, 33L, 33L
), work_hr_03 = c(55L, 35L, 34L), work_hr_04 = c(40L, 39L, 42L
)), class = "data.frame", row.names = c(NA, -3L))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2015-05-25
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多