在R中基于逻辑条件返回列表中的变量名称。

huangapple go评论63阅读模式
英文:

Return names of variables with in list based on logical condition in R

问题

Desired output: "Sex"

英文:

I want to know what independents variables has low frequency based on my dependent variables(PIM1). Since there are a lot variables, I employed apply for xtab. Now, I have a list(infcom) which include xtab outputs. I want to find the name of variables that satisfy my desired frequency. For example, when PIM1 is one, there is only one female in the sample and when PIM1 is zero, there is no female in the sample. I want to find these variables in the list. My criteria is that at least 2 patients represent each levels. In other words, PIM1= one and PIM1=2 does not come from each gender. I want to code return "Sex". I tried use lapply . But, it does not work. I do not any ide how the problem should be solved. I appreciate any help and comments.

patientsID<-c(1:10)
PIM1<-c(1,1,0,1,0,1,1,0,0,1)
Age <- c(65, 65, 68, 68, 68, 70, 70, 70, 70, 68)
Sex <- c('M', 'F', 'M', 'M','M', 'M','M', 'M','M', 'M')
Cop <- c(0,1,0,1,0,1,1,0,1,1)
# Join the variables to create a data frame
df <- data.frame(patientsID,PIM1,Age,Sex,Cop)

infcom<-apply(df[, -1], 2, function(x) xtabs(~df$PIM1+x)) #I remove ID column
infcom

Current output :

$PIM1
       x
df$PIM1 0 1
      0 4 0
      1 0 6

$Age
       x
df$PIM1 65 68 70
      0  0  2  2
      1  2  2  2

$Sex
       x
df$PIM1 F M
      0 0 4
      1 1 5

$Cop
       x
df$PIM1 0 1
      0 3 1
      1 1 5

Desired output:
Sex

答案1

得分: 2

df[-1] |>
lapply(table) |>
lapply(min) |>
Filter(f = (x) x < 2) |>
names()

[1] "Sex"

英文:
df[-1] |&gt;
  lapply(table) |&gt;
  lapply(min) |&gt;
  Filter(f = \(x) x &lt; 2) |&gt;
  names()
# [1] &quot;Sex&quot;

huangapple
  • 本文由 发表于 2023年6月8日 22:47:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定