0

Hi I am new learner of R and I have some question about mutate function like this

KulonProgo_1 <- read_csv("Kulon_Progo_KebutuhanAir.csv")
KulonProgo_1$DESA <- NULL # I delete some column
KulonProgo_1$NO <- NULL # I delete some column
Test <- as_data_frame(t(KulonProgo_1)) 
rownames(Test) <- c("PDAM","SUMUR","MATA_AIR","SUMUR_BOR","AIR_HUJAN","AIR_ISI_ULANG")
colnames(Test) <- c("DESA_JANGKARAN","DESA_SINDUTAN","DESA_PALIHAN","DESA_GLAGAH",
                    "DESA_KALIDENGEN","DESA_PLUMBON","DESA_KEDUNDANG","DESA_DEMEN",
                    "DESA_KULUR","DESA_KALIGINTUNG","DESA_TEMON_WETAN","DESA_TEMON_KULON",
                    "DESA_KEBONREJO","DESA_JANTEN","DESA_KARANG_WULUH","JUMLAH") # I add new column and row names

Test %>%
  mutate(Test, PERSEN_JUMLAH = JUMLAH / sum(JUMLAH)*100) # but after this mutate didn't work the variable still 16 its should be 17 , why this happened ?, thanks for your help
  • 1
    if you want the result of mutate to persist, you need to assign the result of the pipeline to an object.. For example `Test <- Test %>% mutate(...)` Also, don't pass `Test` to mutate if you are using `%>%` – langtang Dec 05 '22 at 14:04
  • You don't need to specify Test in mutate if you're piping. Assign the result and then view the dataframe, can you see the new column? – cgvoller Dec 05 '22 at 14:05
  • 1
    Most R packages utilize "functional" and "copy-on-write" semantics, striving very specifically to avoid or reduce [side-effect](https://en.wikipedia.org/wiki/Side_effect_(computer_science)). This means that using `mutate` _does_ effect change in that the output from `mutate` is the updated frame. However, it does not reach out and update the origin data (`Test` here). There are functions that choose to have side-effect (`data.table` and `quantmod` come to mind), and usually (not always) it is well documented and must be an intentional step by the user. – r2evans Dec 05 '22 at 14:07
  • 1
    To wrap up the first few comments, use either `mutate(Test, new_col = ...)` or `Test %>% mutate(new_col = ...)`, do not include `Test` in the mutate if you choose the latter. After that, reassign it back into `Test` or a new variable such as `Test2 <- Test %>% mutate(new_col = ...)` (in case you wanted to keep the original data around for some reason). – r2evans Dec 05 '22 at 14:09

0 Answers0