gpt4 book ai didi

r - 识别只有 0 个值的列

转载 作者:行者123 更新时间:2023-12-04 11:54:41 25 4
gpt4 key购买 nike

我想帮助解决以下问题:
正如您在下面看到的可执行代码,它生成了一个带点和线的图形。这些点是从我的 df1 生成的数据集。但是请注意,有一些 DR 仅为 0,例如 DR09、DR10 和 DR12。所以我想做一些函数或一些在所有 DR 都为 0 时识别的东西,并且在计算我的 datas 时没有考虑到这些。变量,因为它正在考虑整个 df1数据集。
非常感谢!

library(dplyr)
library(lubridate)
library(tidyverse)

df1 <- structure(
list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28","2021-06-28",
"2021-06-28","2021-06-28","2021-06-28"),
date2 = c("2021-04-02","2021-04-03","2021-04-08","2021-04-09","2021-04-10","2021-07-01","2021-07-02","2021-07-03"),
Week= c("Friday","Saturday","Thursday","Friday","Saturday","Thursday","Friday","Monday"),
DR01 = c(4,1,4,3,3,4,3,6), DR02= c(4,2,6,7,3,2,7,4),DR03= c(9,5,4,3,3,2,1,5),
DR04 = c(5,4,3,3,6,2,1,9),DR05 = c(5,4,5,3,6,2,1,9),
DR06 = c(2,4,3,3,5,6,7,8),DR07 = c(2,5,4,4,9,4,7,8),
DR08 = c(0,0,0,1,2,0,0,0),DR09 = c(0,0,0,0,0,0,0,0),DR010 = c(0,0,0,0,0,0,0,0),DR011 = c(0,4,0,0,0,0,0,0), DR012 = c(0,0,0,0,0,0,0,0)),
class = "data.frame", row.names = c(NA, -8L))

#Generate graph

dmda<-"2021-07-01"

datas<-df1 %>%
filter(date2 == ymd(dmda)) %>%
summarize(across(starts_with("DR"), sum)) %>%
pivot_longer(everything(), names_pattern = "DR(.+)", values_to = "val") %>%
mutate(name = as.numeric(name))
colnames(datas)<-c("Days","Numbers")

attach(datas)
plot(Numbers ~ Days, ylim=c(0,20))

model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 47,b2 = 0))

new.data <- data.frame(Days = seq(min(Days),max(Days),len = 45))
lines(new.data$Days,predict(model,newdata = new.data))
enter image description here

最佳答案

我们可以通过 select 来做到这一点即检查该列是否为数字( is.numeric )和 where all值为 0

library(dplyr)
df1 %>%
select(where(~ is.numeric(.) && all(. == 0))) %>%
names
[1] "DR09" "DR010" "DR012"
如果我们想选择不包含它们的列,则否定( ! )
df1 %>%
select(!where(~ is.numeric(.) && all(. == 0)))
date1 date2 Week DR01 DR02 DR03 DR04 DR05 DR06 DR07 DR08 DR011
1 2021-06-28 2021-04-02 Friday 4 4 9 5 5 2 2 0 0
2 2021-06-28 2021-04-03 Saturday 1 2 5 4 4 4 5 0 4
3 2021-06-28 2021-04-08 Thursday 4 6 4 3 5 3 4 0 0
4 2021-06-28 2021-04-09 Friday 3 7 3 3 3 3 4 1 0
5 2021-06-28 2021-04-10 Saturday 3 3 3 6 6 5 9 2 0
6 2021-06-28 2021-07-01 Thursday 4 2 2 2 2 6 4 0 0
7 2021-06-28 2021-07-02 Friday 3 7 1 1 1 7 7 0 0
8 2021-06-28 2021-07-03 Monday 6 4 5 9 9 8 8 0 0

或在 base R
names(which(sapply(df1, function(x) is.numeric(x) && all(x == 0))))
[1] "DR09" "DR010" "DR012"

关于r - 识别只有 0 个值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69329854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com