[英]Dataframe selection by numeric columns in R
This is very easy to do in python but is tripping me up in 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),]
Giving the error:给出错误:
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)
Returns退货
<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>
How do I approach this in R我如何在 R 中解决这个问题
try this:尝试这个:
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)
It is a bit difficult to answer your question without knowing the exact question requirements and reproducible code.在不知道确切的问题要求和可重现代码的情况下回答您的问题有点困难。 Is this what you after ?
这是你追求的吗?
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),]
You can use sapply
with is.numeric
like this in base R:您可以使用
sapply
与is.numeric
像这样的基础R:
# 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
Then you can do something like this if you only want the rows which has a sum which is greater than 300:然后,如果您只想要总和大于 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
A solution without the non-numeric columns is:没有非数字列的解决方案是:
dat <- dat[sapply(dat, is.numeric)]
dat[rowSums(dat) > 300, ]
#R> A C D
#R> 2 2 2 350
#R> 3 3 3 700
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.