samedi 3 juillet 2021

How to have multiple if, and, or statement in ifelse or subsetting in R dataframe/ [duplicate]

In my dataset, I have altitude data for three sites across four months. The altitude for Jan is already known and prefilled as 1. For the other three months, I have to manually assign the values for each site. I attempted two ways of doing that:

alt <- rep(c(0,0,0,1), each = 3)
site <- rep(c(1,2,3), time = 4)
month <- rep(c("Oct", "Nov","Dec", "Jan"), each = 3)

df <- data.frame(site, month,alt)

#Approach 1
df$alt[df$month == c("Oct","Nov","Dec") & df$site == 1] <-  219
df$alt[df$month == c("Oct","Nov","Dec") & df$site == 2] <-  220
df$alt[df$month == c("Oct","Nov","Dec") & df$site == 3] <-  221

Only Site 1 in Oct, Site 2 in Nov and Site 3 in Dec got filled. The others remained 0.

#Approach 2

df$alt <- with(df$site = 1, ifelse(df$month == c("Oct","Nov","Dec"), 212, df$alt), 
df$alt)

Error: unexpected '=' in "df$alt <- with(df$site ="

I welcome other approaches. Would love to know why my approaches are not working

Aucun commentaire:

Enregistrer un commentaire