【问题标题】:Generate a new variable in r based on condition in one column and value in another column根据一列中的条件和另一列中的值在 r 中生成一个新变量
【发布时间】:2021-07-19 12:21:35
【问题描述】:

我有一个数据框,其中包含有关主题、高度和高度单位的数据

subject <- c(1,2,3,4)
height <- c(100, 90, 56, 64)
height_unit <- c("cm", "cm", "inches", "inches")
complete_file <- data.frame(subject, height, height_unit)

基本上,只要 height_unit 等于英寸,我想做的就是将高度列乘以 2.54。到目前为止,这是我尝试过的:

vital_signs_clean <- vital_signs_clean %>%
     group_by(subject_id) %>%
     mutate(height = if(n_distinct(Height_Units == "inches", na.rm = TRUE) == 1), *2.54)

为此,我收到一条错误消息,指出代码中出现“意外的 'else'”。这是最好的方法还是有更好的建议?

【问题讨论】:

  • 使用ifelse - complete_file %&gt;% mutate(height_in_cm = ifelse(height_unit == 'inches', height * 2.54, height))

标签: r dplyr


【解决方案1】:

这应该可以解决问题:

library(dplyr)
complete_file %>% 
  mutate(height = ifelse(height_unit == "inches", height * 2.54, height))

输出:

  subject height height_unit
1       1 100.00          cm
2       2  90.00          cm
3       3 142.24      inches
4       4 162.56      inches

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2022-10-21
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多