简体   繁体   English

如何基于R中的if条件语句重新编码一组变量中的负值?

[英]How to recode negative values in a set of variables based on if conditional statement in R?

R newbie here. R新手在这里。 I am currently trying to recode a set of variables in R, such that all negative values within them are recoded as positive values. 我目前正在尝试重新编码R中的一组变量,以使其中的所有负值都重新编码为正值。

Please find simulated data below: 请在下面找到模拟数据:

df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
                 measure1 = rnorm(11, mean = 0, sd = 1),
                 measure2 = rnorm(11, mean = 0, sd = 1),
                 measure3 = rnorm(11, mean = 0, sd = 1),
                 measure4 = rnorm(11, mean = 0, sd = 1))

This is the function I've written so far: 这是我到目前为止编写的函数:

df[2:5] <- sapply(df[2:5], function(x) {
  if(x<0) {
  return(x*-1)
}  else {
   return(x)
    }
  })

although I recieve the following errors: 尽管我收到以下错误:

Warning messages:
1: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
3: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
4: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used

Any ideas on how to make this work? 关于如何进行这项工作的任何想法?

Thanks! 谢谢!

您可以使用

df[, 2:5] <- abs(df[, 2:5])

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

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