Home > Mobile >  How to delete attach function of code in R
How to delete attach function of code in R

Time:09-27

How do I generate the graph without using the attach function? Some people said that it's not good to use the attach, but I don't know how to solve it.

Executable code below:

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

#dataset df1
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)),
  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))

CodePudding user response:

In the plot/nls, there is a data option which can be used instead of attaching. It can go out of proportion when there are 1000s of columns i.e. it creates 1000 objects in the global env

plot(Numbers ~ Days, ylim=c(0,20), data = datas)
model <- nls(Numbers ~ b1*Days^2 b2,start = list(b1 = 47,b2 = 0), data = datas)
new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
lines(new.data$Days,predict(model,newdata = new.data))

-output

enter image description here

If we want to extract column values, there are options like $ or [[ and if we have to do this multiple times, use with

CodePudding user response:

There are a few ways, here some:

Use the columns from the data.frame as vectors with operator $

plot(x = datas$Days,y = datas$Numbers, ylim=c(0,20))

enter image description here

An interesting alternative, is to use ggplot2

library(ggplot2)
ggplot(datas,aes(x = Days,y = Numbers)) 
  geom_point(shape = 21,size = 2)

enter image description here

  •  Tags:  
  • r
  • Related