如何解决R中的“ .subset2(x,i,精确=精确)中的错误”问题?

时间:2020-11-08 08:05:27

标签: r matrix

我在R中使用以下数据框:

ID <- c(LETTERS[1:10])
GLUC <- c(88,NA,110,NA,90,88,120,110,NA,90)
TGL <- c(NA,150,NA,200,210,NA,164,170,190,NA)
HDL <- c(32,60,NA,65,NA,32,NA,70,NA,75)
LDL <- c(99,NA,120,165,150,210,NA,188,190,NA)

patient_num <- data.frame(ID,GLUC,TGL,HDL,LDL)

我想创建一个矩阵,其中以GLUC,TGL,HDL和LDL作为行名,并以均值,中位数,sd,n和n_miss作为列名。当我输入以下代码时:

  r <- c(mean(patient_num[[varname]],na.rm=TRUE), 
    median(patient_num[[varname]],na.rm=TRUE), 
    sd(patient_num[[varname]],na.rm=TRUE),
    sum(!is.na(patient_num[[varname]])),
    sum(is.na(patient_num[[varname]]))
    )
  if (length(varname) == 1){
    r <- matrix(r,nrow=T)
  } else{
    for (index in 2:length(varname)){
      oneRow = table1(patient_num,varname[[index]])
      r <- rbind(r,oneRow)
    }
  }
  rownames(r) <- varname
  colnames(r) <- c("mean","median","sd","n","n_miss")
  return(r)
}

table1(patient_num,c("GLUC","TGL","HDL","LDL")) 

我收到一条错误消息:

.subset2(x,i,确切=精确)中的错误:在2级上递归索引失败

似乎无法找出问题所在

2 个答案:

答案 0 :(得分:1)

使用sapply()中的base R有一个更简单的解决方案:

new_df <- sapply(patient_num, function(x) list(
  mean = mean(x, na.rm = T),
  sd = sd(x, na.rm = T),
  n = sum(!is.na(x)),
  is_na = sum(is.na(x))))

t(new_df)

#>     mean     sd       n  is_na
#>ID   NA       NA       10 0    
#>GLUC 99.42857 13.45185 7  3    
#>TGL  180.6667 23.0362  6  4    
#>HDL  55.66667 19.00175 6  4    
#>LDL  160.2857 40.06126 7  3 

如果只希望每行中的非NA条目数,则只需从ID中删除patient_num并运行相同的代码即可。

请注意,您可能希望将new_df转换回data.frame

答案 1 :(得分:0)

使用[[一次只能选择一列。

这是使用dplyr函数的另一种方法。

library(dplyr)

table1 <- function(data, varname) {

  data %>%
    select(all_of(varname)) %>%
    tidyr::pivot_longer(cols = everything()) %>%
    group_by(name) %>%
    summarise(mean = mean(value, na.rm = TRUE), 
              median = median(value, na.rm = TRUE), 
              sd = sd(value, na.rm = TRUE), 
              n = sum(!is.na(value)), 
              n_miss = sum(is.na(value)))
}

table1(patient_num,c("GLUC","TGL","HDL","LDL")) 

# A tibble: 4 x 6
#  name   mean median    sd     n n_miss
#  <chr> <dbl>  <dbl> <dbl> <int>  <int>
#1 GLUC   99.4   90    13.5     7      3
#2 HDL    55.7   62.5  19.0     6      4
#3 LDL   160.   165    40.1     7      3
#4 TGL   181.   180    23.0     6      4
相关问题