Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在%>;%内使用应用函数_R_Apply_Magrittr - Fatal编程技术网

R 在%>;%内使用应用函数

R 在%>;%内使用应用函数,r,apply,magrittr,R,Apply,Magrittr,下面我创建了一个函数,如果特定列中只有一个唯一的值,它将删除该列。我是否可以在%>%内使用lappy来避免调用函数三次?或者甚至调用所有列的函数 df <- tibble(col1 = sample(1:6), col2 = sample(1:6), col3 = 3, col4 = 4) condDelCol <- function(mycolumn, mydataframe) { if(length(unique(mydataframe[[mycolumn]])

下面我创建了一个函数,如果特定列中只有一个唯一的值,它将删除该列。我是否可以在%>%内使用lappy来避免调用函数三次?或者甚至调用所有列的函数

df <- tibble(col1 = sample(1:6), col2 = sample(1:6), col3 = 3, col4 = 4)

condDelCol <- function(mycolumn, mydataframe) {    
    if(length(unique(mydataframe[[mycolumn]])) == 1) { mydataframe[[mycolumn]] = NULL }
    mydataframe
}

df %>% 
condDelCol("col2", .) %>% 
condDelCol("col3", .) %>% 
condDelCol("col4", .)
df%
condDelCol(“col3”,)%>%
condDelCol(“col4”,)

使用
dplyr
,如果

library(dplyr) 
df %>%
   select_if(~ n_distinct(.) > 1)
# A tibble: 6 x 2
#   col1  col2
#  <int> <int>
#1     1     6
#2     6     1
#3     5     5
#4     3     4
#5     4     2
#6     2     3

或使用
过滤器

Filter(var, df)

你也可以用这个。它忽略标准偏差为0的列

df[, sapply(df, sd) != 0]

# A tibble: 6 x 2
   col1  col2
  <int> <int>
1     1     3
2     5     6
3     6     1
4     2     2
5     3     4
6     4     5

您可以这样做
df[,apply(df,2,函数(x)长度(唯一的(x)))>1]
谢谢,也可以在%>%内写sapply吗?
df[, sapply(df, sd) != 0]

# A tibble: 6 x 2
   col1  col2
  <int> <int>
1     1     3
2     5     6
3     6     1
4     2     2
5     3     4
6     4     5
df %>%
  select(which(sapply(df, sd) != 0))