简体   繁体   English

根据一列中的条件和另一列中的值在 r 中生成一个新变量

[英]Generate a new variable in r based on condition in one column and value in another column

I have a dataframe containing data on subject, height, and height unit我有一个包含主题、高度和高度单位数据的数据框

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)

Essentially, what I want to do is multiply the height column by 2.54 any time that the height_unit is equal to inches.本质上,我想要做的是在 height_unit 等于英寸的任何时候将高度列乘以 2.54。 Here is what I have tried so far:这是我迄今为止尝试过的:

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

For this, I received an error stating "unexpected 'else'" in the code.为此,我在代码中收到一条错误消息,指出“意外的‘其他’”。 Is this the best way to go about it or are there better recommendations?这是最好的方法还是有更好的建议?

This should do the trick:这应该可以解决问题:

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

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM