I have a csv file I am importing as a df:
df <- data.frame(mrt = c(1,NA,2,NA,NA,3,NA,NA),
municipio = c("aquidauana",NA,"corumba",NA,NA,"jardim",NA,NA))
and I want to get the following:
mrt municipio
1 aquidauana
1 aquidauana
2 corumba
2 corumba
2 corumba
3 jardim
3 jardim
3 jardim
what I am trying is:
df$municipio <- as.factor(df$municipio)
mrt <- df %>%
fill(mrt) %>%
fill(municipio)
accordingly to fill() documentation, it should work with factor variables but it is not my case. mrt column works fine but municipio column remains the same with no error on console.
Does someone know what is happening and how to solve?
thank you
It worked for me. I had to change your initial df.
library(tidyverse)
df <- data.frame(mrt = c(1,NA,2,NA,NA,3,NA,NA),
municipio = c("aquidauana",NA,"corumba",NA,NA,"jardim",NA,NA)) # these are strings
df$municipio <- as.factor(df$municipio)
df %>%
fill(mrt) %>%
fill(municipio)
mrt municipio
1 1 aquidauana
2 1 aquidauana
3 2 corumba
4 2 corumba
5 2 corumba
6 3 jardim
7 3 jardim
8 3 jardim
the initial df I just wrote here so others could have the same data as me. However I received the a .csv file, which I import to R with
df <- read.csv("path", sep=';', header = T)
df$municipio <- as.factor(df$municipio)
it is now unclear whether you have an issue seeking further support, or whether all is well with the world. can you clarify ?
system
Closed
February 7, 2024, 11:06am
5
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.