【问题标题】:How to use data which belongs to factor data type as argument in function in r如何使用属于因子数据类型的数据作为r函数中的参数
【发布时间】:2018-08-04 11:55:40
【问题描述】:

我的数据是这种格式,尤其是性别和种族是因素。

>head(scr)
  age scr    sex ethnic
1  48 1.2 Female  Other
2   7 0.8   Male  Black
3  62 1.8 Female   <NA>
4  48 3.8 Female  Other
5  51 1.4   Male  Other

函数主要是计算方程: enter image description here 但是当我输入数据时,它显示性别和种族参数缺失,没有默认值。

egfr.mdrd4(scr[1,])

那么,如何改变性别和种族的函数或数据类型来运行这个函数呢?

egfr.mdrd4 <- function(scr, age, sex, ethnic){
  if (sex == "Female")
    n<-0.742
  else
    n<-1
  if (ethnic == "Black")
    m<-1.212
  else
    m<-1
  mdrd<-175*scr^(-1.154)*age^(-0.203)*n*m
return (mdrd) 
}
egfr.md(scr[1,])

【问题讨论】:

  • 试试if (as.character(sex) == "Female")ethnic 一样。
  • 您也可以将sexethnic 转换为字符:例如:scr$sex &lt;- as.character(scr$sex)
  • 谢谢你的帮助,这个方法我已经试过了。

标签: r function debugging arguments


【解决方案1】:

有几个问题:

  • egfr.mdrd4 接受 4 个参数,但问题中显示的代码将其传递给一个参数

  • scr 数据框中的列与egfr.mdrd4 的参数顺序不同

  • 如果因子列中存在非级别的 NA 值,则代码会尝试比较 NA

  • 代码未矢量化(这可能对您来说是个问题,也可能不是)

试试这个。代码已修改为传递单个参数 scr 而不是 4 个参数。

我们还将addNA(sex)"Female"addNA(ethnic)"Black" 进行比较,这将导致添加任何NA 作为因子级别,以便将NA 与指示的字符串进行比较导致采用假腿。 (使用addNA 的替代方法是使用!is.na(sex) &amp;&amp; sex == "Female" 之类的条件,这对于NA 也是错误的。它使用短路&& 运算符,仅在左侧为真时才评估其右侧。)

此外,if 已使用ifelse 进行了矢量化处理。

egfr.mdrd4v2 <- function(scr) with(scr, {
  n <- ifelse(addNA(sex) == "Female", 0.742, 1)
  m <- ifelse(addNA(ethnic) == "Black", 1.212, 1)
  mdrd <- 175*scr^(-1.154)*age^(-0.203)*n*m
  mdrd
})
egfr.mdrd4v2(scr)
## [1]  47.94848 184.85020  28.51031  12.67885  53.42808

注意

可重现形式的输入scr

scr <- structure(list(age = c(48L, 7L, 62L, 48L, 51L), scr = c(1.2, 
0.8, 1.8, 3.8, 1.4), sex = structure(c(1L, 2L, 1L, 1L, 2L), .Label = c("Female", 
"Male"), class = "factor"), ethnic = structure(c(2L, 1L, NA, 
2L, 2L), .Label = c("Black", "Other"), class = "factor")), .Names = c("age", 
"scr", "sex", "ethnic"), row.names = c("1", "2", "3", "4", "5"
), class = "data.frame")

更新

根据 cmets 修改。

【讨论】:

  • 感谢您的帮助,但是如果民族标签是“”,函数的结果会是,如何改成数字呢?
  • 已经修改了我假设的输入并相应地修改了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 2018-05-11
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2015-09-12
相关资源
最近更新 更多