按R中的数字列选择数据帧



这在python中很容易做到,但在R.中会绊倒我

numeric_cols<-data_all %>% select_if(is.numeric)
columns <-colnames(numeric_cols)
data_all[colnames] # returns dataframe selection
data_all[which(rowSums(data_all[colnames]) > 300),]

给出错误:

Warning message in cbind(parts$left, ellip_h, parts$right, deparse.level = 0L):
“number of rows of result is not a multiple of vector length (arg 2)

rowSums(data_wideALL[colnames] > 300)

返回

<NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA><NA>

如何在R 中处理此问题

试试这个:

numeric_cols <- data_all %>%
select_if(is.numeric)
num_cols <- names(numeric_cols)
data_all <- data_all %>%
select(num_cols) 
data_all$row_sum <- rowSums(data_all)
data_all <- data_all %>%
filter(row_sum > 300)

在不知道确切的问题要求和可复制代码的情况下回答您的问题有点困难。这就是你想要的吗?

numeric_cols<-data_all %>% select_if(is.numeric)
columns <-colnames(numeric_cols)
data_all<-data_all[columns] # returns dataframe selection
data_all[rowSums(data_all[columns] > 300),]

在基本R:中,可以像这样将sapplyis.numeric一起使用

# assign a data set
dat <- data.frame(A = c(1L, 2L, 3L), B = c(TRUE, TRUE, FALSE), 
C = c(1, 2, 3), D = c(50, 350, 700))
# use sapply + is.numeric
dat[sapply(dat, is.numeric)]
#R>   A C   D
#R> 1 1 1  50
#R> 2 2 2 350
#R> 3 3 3 700

然后,如果你只想要总和大于300:的行,你可以做这样的事情

dat[rowSums(dat[sapply(dat, is.numeric)]) > 300, ]
#R>   A     B C   D
#R> 2 2  TRUE 2 350
#R> 3 3 FALSE 3 700

没有非数字列的解决方案是:

dat <- dat[sapply(dat, is.numeric)]
dat[rowSums(dat) > 300, ]
#R>   A C   D
#R> 2 2 2 350
#R> 3 3 3 700

最新更新